Search code examples
javascriptmomentjsmoment-timezone

Moment timezone returning property 'preparse' of null


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/


Solution

  • You have to use moment.tz instead of moment(String) since you are passing the timezone ('Asia/Bangkok') parameter.

    Your code could be like the following:

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

    Here a working snippet based on the linked 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>