I have a Vue application, I am trying to convert a long UTC datetime string to a local time Javascript object, this is my string:
Mon Apr 10 2023 23:19:45 GMT+0000 (Coordinated Universal Time)
I have tried (unsuccessfully):
Date.parse(string);
and
new Date(string);
Which is leaving me with something like this:
var dt = myDate.split(/-|s/)
dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);
But this does not seem efficient?
I need to do this over a 500 object JSON, so want to ensure I am doing it as efficient as possible.
2
Answers
If you can possibly avoid storing the date in that format, you will save a lot of headache
Although the string is in UTC, it is in a particular language and locale. It just happens to be English and UTC which is handy for you and me to read by eye, but there is no guarantee that the user’s browser will be in this language/locale.
If at all possible, store the date/time in ISO format, which is
Example if ISO-8601:
You can tweak it to a particular language and timezone for display purposes, but I suggest always storing it in ISO.
An example of why never to store anything other than ISO format in your data, is the very problem you are facing.
Presumably you only need to fix it once, to extract the data? If so, make sure you are using a standard browser (e.g. up to date Chrome), have set the language to English, and try out the example shown by @Dimava
I get this, which is correct, but unhelpful:
You can then convert all of them into a sensible format:
Are you sure the
fromClientDateTime
variables are actually strings?I suspect they may be Javascript DateTime objects. If so, you can convert them to ISO format as follows:
The reason I suspect that is when I
console.log
a string property in Chrome, I get quotation marks. The way to get no quotation marks (as you have in your image), is to have the property be a DateTime object, not a string.