javascript 尝试格式化日期,总是得到无效的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22783419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trying to format date, always getting invalid date
提问by Upvote
The user selects a date from a jquery datepicker, it has following format:
用户从 jquery 日期选择器中选择一个日期,它具有以下格式:
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.
当用户提交表单时,我想使用 moment 将日期输入转换为 UTC。但是,无论我对输入做什么,都会出现Invalid Date
错误。
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.
好像那个时候不能解析输入,可以解析MM.DD.YY格式,但是输入必须是DD.MM.YYYY格式。
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) }
回答by Peter
Consider using moment's hinting support:
考虑使用 moment 的提示支持:
moment(input, 'DD.MM.YYYY')
A Fiddle demonstrating the approach is available here:
演示该方法的小提琴可在此处获得:
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.
Moment 将假定本地时间输入,因此如果您在该时区之外工作,您可能需要将时区附加到您的输入中。请参阅http://momentjs.com/docs 上的文档- 特别是 parseZone() 和“String + Format”部分。
In the case of server-side (node), you are probably getting odd results because of the server's timezone.
在服务器端(节点)的情况下,由于服务器的时区,您可能会得到奇怪的结果。