skip to Main Content

When converting the date string ’06/06/2022′ to a date object in my local node environment using the following code…

new Date('06/06/2022')

The resulting date object is ‘2023-06-05T23:00:00.000Z’.
The day is being changed.

I understand that I can use .toLocaleDateString() to convert this back. But I require the date object itself.

How do I get the locale date object, instead of the locale date string?

3

Answers


  1. Chosen as BEST ANSWER

    As MC emperor mentioned, the local machine date is out from UTC by 1 hour.

    I was attempting to equate 2 date values whilst writing server tests and running the server locally.

    To handle this in the short term at least I have used the following solution.

    // '2023-06-05T23:00:00.000Z' this date is being generated within the test code
    date1 = new Date('06/06/2022')
    
    // '2023-06-05T00:00:00.000Z' this date is being generated by a DB ORM and returned from the unit test function
    date2 = new Date(dResponse)
    

    To equate the 2 dates. I have normalized the UTC values using .setUTCHours(0) Another solution may have been to simply add a day to the ORM response for the purposes of equating the test.

    However both of these are simply hacks/workarounds. I am unsure as to a perfect solution here.


  2. Maybe you should not use the date object, as it represents a timezone-agnostic timestamp, and uniquely defines an instant in history. the problem you are facing is the display of node.

    If you only focus on the day, you have options like:

    Passing date as a text value: ’06/06/2022′

    this will not be accurate if you use the value in different timezones

    If you only want the node console to be correct, you can change timezone of node environment to something like:

    process.env.TZ = 'Europe/Madri';
    new Date('06/06/2022');
    
    Login or Signup to reply.
  3. I have found a further solution using the answer provided by monster club at the following SO link..

    creating date as UTC

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search