skip to Main Content

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)

enter image description here

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


  1. 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

    • easy for code to read and write
    • compact
    • easy to sort

    Example if ISO-8601:

    2023-04-10T21:57:02Z
    

    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

    new Date('Mon Apr 10 2023 23:19:45 GMT+0000 (Coordinated Universal Time)')
    

    I get this, which is correct, but unhelpful:

    Tue Apr 11 2023 00:19:45 GMT+0100 (British Summer Time)
    

    You can then convert all of them into a sensible format:

    new Date('Mon Apr 10 2023 23:19:45 GMT+0000 (Coordinated Universal Time)').toISOString()
    
    
    '2023-04-10T23:19:45.000Z'
    

    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:

    fromClientDateTime.toISOString()
    

    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.

    const a = {x: new Date(), y: "Example string"}
    
    a
    {x: Mon Apr 10 2023 23:05:53 GMT+0100 (British Summer Time), y: 'Example string'}
    
    Login or Signup to reply.
  2. const utcDateStr = 'Mon Apr 10 2023 23:19:45 GMT+0000 (Coordinated Universal Time)';
    const utcDate = new Date(utcDateStr);
    const localDate = new Date(utcDate.getTime() - utcDate.getTimezoneOffset() * 60000);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search