I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.
I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.
Share Improve this question asked Jul 21, 2014 at 21:36 user3845941user3845941 2053 silver badges16 bronze badges 8-
Because
Wed Apr 30 2014 18:00:00 + 06 h
==Thur May 01 2014 00:00:00 GMT
. – dfsq Commented Jul 21, 2014 at 21:40 - I see....sorry I mocked in some data – user3845941 Commented Jul 21, 2014 at 21:41
- You get time in GMT-0600 timezone. – dfsq Commented Jul 21, 2014 at 21:42
-
maybe it has something to do with your system time ... it works fine for me , here is the result
Thu May 01 2014 01:00:00 GMT+0100 (GMT (heure d’été))
– Khalid Commented Jul 21, 2014 at 21:42 - That is odd why I get Apr 30 2014 18:00:00? I get that in JSFiddle as well – user3845941 Commented Jul 21, 2014 at 21:45
2 Answers
Reset to default 5I resolved the issue with the following:
var date = new Date(indexPie);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var dateString = year + "-" + month + "-" + day;
You are expecting that the value in date
variable: "2014-05-01"
will be parsed as in local timezone, but actually it is parsed as in UTC.
You can convert the date from UTC to local timezone like this:
var newDate = new Date(indexPie + new Date().getTimezoneOffset() * 60000);