Search code examples
javascriptnode.jsdatemomentjsmoment-timezone

How can I validate the formate of a date string that has timezone in it?


If I have a this date: April 14, 2022 14:00 UTC, how I can validate that it is in MMMM DD, YYYY HH:mm <timezone>?

I tried it with moment but it doesn't have format for timezone.

moment(date, 'MMMM DD, YYYY HH:mm',true).isValid()

How can I validate that the string is in MMMM DD, YYYY HH:mm <timezone> format?


Solution

  • You can include " UTC" as literal text in the parse format, e.g.

    let date = 'April 14, 2022 14:00 UTC';
    
    console.log(
      moment(date, 'MMMM DD, YYYY HH:mm[ UTC]',true).isValid()
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

    Per the moment.js documentation, various offset formats are supported, so if there are other offset representations you can use multiple tests to support say "UTC" and "+00:00" (or ±HH:mm in general), e.g.

    ['April 14, 2022 14:00 UTC',
     'April 14, 2022 14:00 +00:00',
     'April 14, 2022 14:00 +05:30'
     ].forEach(date => 
        console.log(`${date} is valid? ` +
        `${moment(date, 'MMMM DD, YYYY HH:mm[ UTC]', true).isValid() ||
           moment(date, 'MMMM DD, YYYY HH:mm Z', true).isValid()}`
        )
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

    Unfortunately isValid doesn't support multiple formats in the one call so you can't do:

    moment(date, 'MMMM DD, YYYY HH:mm[ UTC]',  'MMMM DD, YYYY HH:mm Z', true).isValid()
    

    as only the first format is recognised.