Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"getDate().toJSON()" loses a day

I'm using the pikaday date picker plugin (through an angular directive and with momentjs) and sending the value to the server. Converting to json seems to lose a day though:

var d = myPikaObject.getDate();
console.log(d);              // Thu Apr 30 2015 00:00:00 GMT+0200 (SAST)
console.log(d.toJSON());     // 2015-04-29T22:00:00.000Z

I think this is a momentjs problem but I have no idea what's going wrong.

like image 500
jcuenod Avatar asked Apr 29 '15 14:04

jcuenod


2 Answers

It's all about the format of your date.

When you juste print d, you have this :

Thu Apr 30 2015 00:00:00 GMT+0200 (SAST)

It's GMT +2, so when you print d.ToJson() you lost 2 hours. So you are the day before at 22pm

like image 184
Pierre-Alexandre Moller Avatar answered Sep 21 '22 23:09

Pierre-Alexandre Moller


Giving you're already getting time with momentjs, you can try moment.utc() method. The docs say:

As of version 2.0.0, a locale key can be passed as the third parameter to moment() and moment.utc()

moment('2012 juillet', 'YYYY MMM', 'fr');
moment('2012 July',    'YYYY MMM', 'en');

You can do a lot more with the utc() method.

moment.utc();
moment.utc(Number);
moment.utc(Number[]);
moment.utc(String);
moment.utc(String, String);
moment.utc(String, String[]);
moment.utc(String, String, String);
moment.utc(Moment);
moment.utc(Date);
like image 35
ilter Avatar answered Sep 18 '22 23:09

ilter