Skip to content
Advertisement

Convert a string to date in JavaScript

I have the following string and I want to convert it to Date

'20220722T141444Z'

In C# I converted it by telerik’s DateParser library.

Is there a way to convert it in JavaScript as well?

Answer

There are many questions on parsing timestamps. In this case, you can just get the parts as two digit pairs then use that to call the Date constructor.

Since the timestamp has a trailing “Z”, likely it should be parsed as UTC so:

let ts = '20220722T141444Z'
let [C,Y,M,D,H,m,s] = ts.match(/dd/g) || [];
let date = new Date(Date.UTC(C+Y, M-1, D, H, m, s));

console.log(date.toISOString());

There are many other ways to approach the problem, such as modifying the values to create a supported format such as `2022-07-22T14:14:44Z’, however it’s more efficient to give the parts directly to the Date constructor than to build a string then have the built–in parser parse it.

Advertisement