Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 don't catch to error message
  • Date.parse() change the format of string date to 1317826080000 so to could not compare it to ISO or UTC format.

I would avoid using libraries like moment.js

like image 854
infodev Avatar asked Oct 18 '18 08:10

infodev


2 Answers

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

  • Date: 2018-10-18
  • Combined date and time in UTC: 2018-10-18T08:04:30+00:00 (without the Z and TZ in 00:00)
  • 2018-10-18T08:04:30Z
  • 20181018T080430Z
  • Week: 2018-W42
  • Date with week number: 2018-W42-4
  • Date without year: --10-18 (last in ISO8601:2000, in use by RFC 6350[2]) *Ordinal date: 2018-291

function isIsoDate(str) {
  if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(str)) return false;
  var d = new Date(str); 
  return d.toISOString()===str;
}

console.log(isIsoDate('2011-10-05T14:48:00.000Z'))

console.log(isIsoDate('2018-11-10T11:22:33+00:00'));
like image 140
mplungjan Avatar answered Oct 08 '22 19:10

mplungjan


I think what you want is:

let date= '2011-10-05T14:48:00.000Z';
const dateParsed = new Date(Date.parse(date))

if(dateParsed.toISOString() === date && dateParsed.toUTCString() === new Date(d).toUTCString()){
   return  date;
} else {
     throw new BadRequestException('Validation failed'); 
}

I hope that is clear!

like image 36
Hasan Sh Avatar answered Oct 08 '22 19:10

Hasan Sh