片刻时区返回的属性'preparse'为null

时间:2018-07-11 15:22:56

标签: javascript momentjs moment-timezone

试图解析某个日期时

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

我收到错误 typeError:无法读取null的属性“ preparse”

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

2 个答案:

答案 0 :(得分:1)

由于要传递时区('Asia/Bangkok')参数,因此必须使用moment.tz而不是moment(String)

您的代码可能如下:

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>

答案 1 :(得分: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");