Moment.js将日期字符串转换为日期 [英] Moment.js to convert date string into date
问题描述
紧随我之前的文章: JavaScript Safari:键入新的带字符串的Date()时,返回无效日期 我正在使用Moment.js根据用户在文本框中的输入将日期字符串转换为日期字段.这是为了防止我在Safari和Firefox的链接文章中描述的问题(Chrome正常时无法呈现日期). 这是代码窃听器:
Following up from my previous post: Javascript Safari: new Date() with strings returns invalid date when typed I am using Moment.js to convert a date string into a date field based on user input in the text box. This is to prevent the problem I described in the linked post for Safari and Firefox not able to render the date, when Chrome is fine. Here is the code snipper:
var tempDate = moment(userInputFieldDate).format('DD-MM-YYYY');
alert(tempDate);
在Chrome中,它确实可以正常工作(它也可以与Javascript Date对象一起使用),但给了我moment.js弃用警告
In Chrome, it does work fine (it use to work with the Javascript Date object too) but gives me the moment.js deprecation warning
弃用警告:构建时间回落到js日期.不建议这样做,并将在即将发布的主要版本中将其删除.请参阅 https://github.com/moment/moment/issues/1407 更多信息. 参数:[object Object] 错误
Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info. Arguments: [object Object] Error
在Firefox和Safari上,仅在警报窗口中提供一个不确定的日期.因此,不能完全确定我应该怎么做才能将日期字符串转换为Date对象.有什么建议吗?
On Firefox and Safari is just gives an UNDEFINED DATE in the alert window. So not entirely sure what should I be doing to convert the date string to Date object. Any suggestions ?
推荐答案
如果要获取基于JS的日期String
,请首先使用new Date(String)
构造函数,然后将Date
对象传递给moment
方法.喜欢:
If you are getting a JS based date String
then first use the new Date(String)
constructor and then pass the Date
object to the moment
method. Like:
var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
如果dateString
是15-07-2016
,则应使用>
var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15
这篇关于Moment.js将日期字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!