Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validating JavaScript datetimeZone format

I can validate the format of this dates using moment library:

2022-03-26T14:15:51 ("YYYY-MM-DDTHH:mm:ss")
2022-03-26 ("YYYY-MM-DD")

But having problem with following :

2022-03-26T14:15:51.667778+03:00  ("YYYY-MM-DDTHH:mm:ss.SSSZ") - this format not solving the problem.

Is there any solution? Maybe using regex will solve?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could try the format YYYY-MM-DDTHH:mm:ss.SSSSSSZ, I’d also suggest using strict mode when parsing dates. This format will allow a variable amount of digits after the decimal point but will refuse to parse a date with no fractional seconds:

function validateDate(input, format) {
    const dt = moment(input, format, true);
    return dt.isValid();
}

const testInputs = [
    '2022-03-26T14:15:51.667778+03:00',
    '2022-03-26T14:15:51.667+03:00',
    '2022-03-26T14:15:51+03:00',
    '2022-03-26T14:15:51',
    'FOO'
]

const format = 'YYYY-MM-DDTHH:mm:ss.SSSSSSZ';

console.log('Input'.padEnd(36), 'Valid');
testInputs.forEach(input => console.log(input.padEnd(36), validateDate(input, format)))
.as-console-wrapper { max-height: 100% !important; }
<script src="https://momentjs.com/downloads/moment.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading