1

While trying to parse a certain date

moment('07/07/2018', 'MM/DD/YYYY', 'Asia/Bangkok')

I receive the error typeError: cannot read property 'preparse' of null

http://jsfiddle.net/uq99udc9/7978/

4

2 回答 2

1

您必须使用moment.tz而不是,moment(String)因为您正在传递 timezone ( 'Asia/Bangkok') 参数。

您的代码可能如下所示:

moment.tz('07/07/2018', 'MM/DD/YYYY', 'Asia/Bangkok')

这是一个基于链接小提琴的工作片段:

$(function(){
  setInterval(function(){
    var divUtc = $('#divUTC');
    var divLocal = $('#divLocal');  
    //put UTC time into divUTC  
    divUtc.text(moment.utc().format('YYYY-MM-DD HH:mm:ss'));      
    
    //get text from divUTC and conver to local timezone  
    var localTime  = moment.utc(divUtc.text()).toDate();
    localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
    divLocal.text(localTime);  
      
    $('#divT').text(moment.tz('07/07/2018', 'MM/DD/YYYY', 'Asia/Bangkok').format('YYYY-MM-DD HH:mm:ss'));
  },1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.17/moment-timezone-with-data-2012-2022.min.js"></script>

UTC<br/>
<div id="divUTC"></div><br/>
Your Local Time with respect to above UTC time<br/>
<div id="divLocal">
</div>    
<br/>Thailand date time<br/>
<div id="divT">
</div>

于 2018-07-11T15:41:04.510 回答
0

如果您在 nodejs 中观察到这个错误,这是绕过它的方法:

var moment = require('moment');
require('moment-timezone'); // important, if you remove this, it will crash
var mtz = moment.tz;
m=mtz("Mon Aug 22 23:32:59 +0000 2016", "ddd MMM DD HH:mm:ss Z YYYY", "UTC");
m.format("YYYY");
于 2019-11-24T06:32:30.620 回答