Search code examples
javascriptdatemomentjsmoment-timezone

Check if date has already been parsed with moment


I am passing down a date string which needs to be parsed appropriately with moment. The problem is in some circumstances it is getting parsed twice, which causes it to become undefined.

this is what the code currently looks like:

moment.tz(dt, 'MMMM D, YYYY', timezone).toDate()

When I parse it the second time, I get:

moment.invalid(/* 2018-09-21T05:00:00.000Z */)

Which causes when I do toDate() to become undefined.

while the first time I will get exactly what I expect:

'2019-02-01T05:00:00.000Z'

Before doing any of this I would like to check if it already if in the format I expect it to be. How do I do this?


Solution

  • You could potentially use the isValid() method to check if the parsing worked before calling toDate(). Demo:

    var timezone = "America/Los_Angeles";
    var dt = 'Sept 21, 2018';
    var m = moment.tz(dt, 'MMMM D, YYYY', timezone);
    var converted = m.toDate().toString();
    console.log(converted);
    
    var x = moment.tz(converted, 'MMMM D, YYYY', timezone);
    console.log(x.isValid());
    //if parsing worked, use the new value
    if (x.isValid()) {
      console.log(x.toDate());
    }
    // if not, assume it's already the correct format and just use that
    else
    {
      console.log(converted);
    }
    <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.21/moment-timezone-with-data.min.js"></script>