Moment.js-如何将日期字符串转换为日期? [英] Moment.js - How to convert date string into date?
问题描述
紧随我之前的文章: JavaScript Safari:键入新的带字符串的Date()时,返回无效日期
我正在使用 Moment.js 转换日期根据文本框中的用户输入将字符串输入日期字段。
I am using Moment.js to convert a date string into a date field based on user input in the text box.
这是为了防止我在Safari和Firefox的链接文章中描述的问题无法在Chrome正常的情况下显示日期。
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.
这是代码片段:
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 a Date object.
对此问题有任何建议吗?
Any suggestions on this issue?
推荐答案
如果基于JS的日期 String
,然后首先使用 new Date(String)
构造函数,然后传递日期
对象作为瞬间
方法。像这样:
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
是 2016年7月15日
,那么您应该使用 moment(date:String,format:String)
方法
In case dateString
is 15-07-2016
, then you should use the moment(date:String, format:String)
method
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屋!