Question

The user selects a date from a jquery datepicker, it has following format:

DD.MM.YYYY

When the user submits the form, I want to transform the date input to UTC using moment. However whatever I do with the input, I get a Invalid Date error.

E.g. input is

30.03.2014

I try to format:

console.log(moment(input).format('MM/DD/YY')); <-- prints Invalid Date

I try to

console.log(moment(input).utc().toDate()); <-- prints invalid date

It seems that moment cannot parse the input, it can parse MM.DD.YY format, however the input must have DD.MM.YYYY format.

Any ideas whats wrong?


Using

moment(input, 'DD.MM.YYYY')

gives me:

{ from: '01.03.2014', to: '30.03.2014' }
{ from: Sat Mar 01 2014 00:00:00 GMT+0100 (CET),
  to: Tue Apr 01 2014 11:00:00 GMT+0200 (CEST) }
Était-ce utile?

La solution

Consider using moment's hinting support:

moment(input, 'DD.MM.YYYY')

A Fiddle demonstrating the approach is available here:

http://jsfiddle.net/x4Xm3/

Moment will assume local time inputs, so if you are working outside of that timezone you may want to append the timezone to your input. See the docs at http://momentjs.com/docs - in particular parseZone() and "String + Format" sections.

In the case of server-side (node), you are probably getting odd results because of the server's timezone.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top