Prosto Trader
Prosto Trader

Reputation: 3527

parse Date from string with locale timeshift js

I have a string: "2014-01-22T09:44:06"

I want to parse it to the same Date object. Here is what I do:

var dateString = "2014-01-22T09:44:06";
var myDate = Date.parse(dateString);
console.log(new Date(myDate));

Here is what i get:

 Wed Jan 22 2014 13:44:06 GMT+0400 (Московское время (зима)) 

Date object is 4 hours shifted compared to original string. How do I eliminate that shift?

Upvotes: 3

Views: 645

Answers (1)

RononDex
RononDex

Reputation: 4183

To get the timezone offset:

You can use the function getTimezoneOffset() which returns your timezone offset in minutes:

var dateString = "2014-01-22T09:44:06";
var myDate = new Date(Date.parse(dateString));
console.log(myDate);
console.log(myDate.getTimezoneOffset());

In your case this will output 240

http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp


To get the UTC dateTime you can use following functions:

getUTCDate()           Returns the day of the month, according to universal time (from 1-31)
getUTCDay()            Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear()       Returns the year, according to universal time (four digits)
getUTCHours()          Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds()   Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes()        Returns the minutes, according to universal time (from 0-59)
getUTCMonth()          Returns the month, according to universal time (from 0-11)
getUTCSeconds()        Returns the seconds, according to universal time (from 0-59)
toUTCString()          Converts a Date object to a string, according to universal time

In your case you can use simply the toUTCString() function:

var dateString = "2014-01-22T09:44:06";
var myDate = new Date(Date.parse(dateString));
console.log(myDate);
console.log(myDate.toUTCString());
console.log(myDate.getTimezoneOffset());

Upvotes: 2

Related Questions