在尝试解析某个日期时
moment('07/07/2018', 'MM/DD/YYYY', 'Asia/Bangkok')
我收到错误typeError:无法读取null的属性"prepare">
http://jsfiddle.net/uq99udc9/7978/
您必须使用moment.tz
而不是moment(String)
,因为您正在传递时区('Asia/Bangkok'
(参数。
您的代码可能如下所示:
moment.tz('07/07/2018', 'MM/DD/YYYY', 'Asia/Bangkok')
这里有一个基于链接fiddle的工作片段:
$(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>
如果您在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");