Reputation: 8992
I have strings like "2014-06-12T23:00:00", i want to turn these strings into time object to be able to add hours to it.
I tried several converting and parsing but didn't work. What is the proper way turning these into time objects?
Upvotes: 2
Views: 5557
Reputation: 24648
Here is how you can add hours to a date object:
var k = "2014-06-12T23:00:00";
var t = new Date( k.replace('T', ' ') ).getTime();
var n = t + 5 * 60 * 60 * 1000; //add 5 hours;
console.log( k, new Date( t ), new Date( n ) );
Are you interested in a particular timezone?
Upvotes: 1
Reputation: 129832
Your string has a valid format, so you could turn it to a Date object by simply typing:
var date = new Date("2014-06-12T23:00:00");
However, the string will be interpreted as an UTC string. When you work with it in the client, the local representation of that value will be used. If you're running that code in a computer running Central Europe time, where time zone is UTC+1h, and June 12 is during daylight savings time, adding an additional hour, date.getDate()
, for instance, will correctly yield 13
(not 12), as 11pm June 12 UTC is actually 1am June 13 local time.
If you don't want the string you provide to be interpreted as UTC time, you may specify a time zone:
var date = new Date("2014-06-12T23:00:00 GMT+0200");
If you want the date to always be considered a local time, you can manually adjust for the offset:
var date = new Date("2014-06-12T23:00:00");
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
Upvotes: 2