简体   繁体   中英

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

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'));

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!

let date= '2011-10-05T14:48:00.000Z';
var dateParsed= new Date(Date.parse(date));
//dateParsed
//output: Wed Oct 05 2011 19:48:00 GMT+0500 (Pakistan Standard Time)
if(dateParsed.toISOString()==date) {
   //Date is in ISO
}else if(dateParsed.toUTCString()==date){
  //DATE os om UTC Format
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM