最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Trying to format date, always getting invalid date - Stack Overflow

programmeradmin2浏览0评论

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) }

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) }
Share Improve this question edited Apr 1, 2014 at 11:01 DarkLeafyGreen asked Apr 1, 2014 at 10:38 DarkLeafyGreenDarkLeafyGreen 70.4k135 gold badges390 silver badges615 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 13

Consider using moment's hinting support:

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

A Fiddle demonstrating the approach is available here:

http://jsfiddle/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./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.

发布评论

评论列表(0)

  1. 暂无评论