Adding hours and minutes to a date with javascript

冷暖自知 提交于 2019-12-12 14:35:15

问题


I am building a meeting calendar based on time zones around the world. My problem is how to add or subtract the time zone from the user selected date in Javascript.

For example, on the select form, the user will select the date from a form: I would then get the results and convert to a date as below...

var ldSelectDate = new Date(document.form1.year.value,
           document.form1.month.value,
           document.form1.day.value);

I would like to add 12 midnight to this object.

I then read in an XML that gets the time zone difference in a string between two cities: such as "+0430" for Kabul or "-0400" for New York (on daylight savings time). This is based on GMT,.

I then calculate the time zone difference between the two cities: which will return the string of "830". (I assume I have to return this as a date object?). I got this part done returning a string. I'm working with strings.

I then want to loop through the 24 hours of the day, set Kabul at 12 midnight and then loop through. I can most likely figure this out - that is, set the date with the whole hours as I loop.

My problem is painlessly subtract the "830" from Kabul to see what the meeting time will be in New York.

It will be ideal if I can just subtract the hours and the minutes from the Kabul time. I noticed on here someone subtracting the hours in javascript, but not the minutes. BTW, that post didn't work for me.

I did this with strings without the minutes, but I mess up with the minutes. There has to be an easier way.

I would take a solution in either native Javascript or jQuery.

Again, I need to subtract/add the time zone difference in hours and minutes to a certain date.

Thanks


回答1:


date.setMinutes(date.getMinutes()+minutesToAdd);

The above code will set your date object ahead by the amount of minutes in the minutesToAdd variable




回答2:


Easiest would be to calculate the minutes for that time delta then do a minutes delta.

date.setMinutes(date.getMinutes() - (hours*60+minutes))


来源:https://stackoverflow.com/questions/6734367/adding-hours-and-minutes-to-a-date-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!