javascripttypescriptvalidationdatetime

Check if a date string is in ISO and UTC format


I have a string with this format 2018-02-26T23:10:00.780Z I would like to check if it's in ISO8601 and UTC format.

let date= '2011-10-05T14:48:00.000Z';
const error;
var dateParsed= Date.parse(date);
if(dateParsed.toISOString()==dateParsed && dateParsed.toUTCString()==dateParsed) {
  return  date;
}
else  {
  throw new BadRequestException('Validation failed');
}

The problems here are:

I would avoid using libraries like moment.js


Solution

  • Try this - you need to actually create a date object rather than parsing the string

    NOTE: This will test the string AS YOU POSTED IT.

    YYYY-MM-DDTHH:MN:SS.MSSZ

    It will fail on valid ISO8601 dates like

    It will no longer accept INVALID date strings

    function isIsoDate(str) {
      if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(str)) return false;
      const d = new Date(str); 
      return !isNaN(d.getTime()) && d.toISOString()===str; // valid date 
    }
    
    console.log(isIsoDate('2011-10-05T14:48:00.000Z')); // correct according to your spec
    
    console.log(isIsoDate('2018-11-10T11:22:33+00:00')); // correct date string but does not use Z
    
    console.log(isIsoDate('2011-10-05T14:99:00.000Z')); // invalid time part