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:
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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With