date moment 字符串 转,Moment.js将日期字符串转换为日期

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

In Chrome, it does work fine (it use to work with the Javascript Date object too) but gives me the moment.js deprecation warning

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

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 ?

解决方案

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值