Search code examples
javascriptdatetimeisodate

Get date ISO string without conversion to UTC timezone


Is there a way in JavaScript to obtain an ISO string of a new Date object:

  • while maintaining the original local timezone (i.e. not converting to UTC)
  • with time component set to midnight
  • without resorting to manually rebuilding a new Date via individual date parts and reformatting the result?

I've been trying this

var date = new Date();
date.setHours(0, 0, 0, 0);
document.write(date.toISOString());

and I am getting this

2017-04-20T04:00:00.000Z

I want to get this

2017-04-20T00:00:00.000

(The lack of the trailing Z would indicate local time)

Essentially, I want a local timezone string, but formatted in the the "ISO" way. Relying on the "toLocale..." formatter method of JS Date provides inconsistent results depending on the locale settings.

Is there a built-in function or way as I've been trying to do to get the desired output (without rebuilding a date object with the date parts)?


Solution

  • Just use setUTCHours instead of setHours and compensate for timezone:

        var date = new Date();
        var timezoneOffset = date.getMinutes() + date.getTimezoneOffset();
        var timestamp = date.getTime() + timezoneOffset * 1000;
        var correctDate = new Date(timestamp);
        
        correctDate.setUTCHours(0, 0, 0, 0);
        document.write(correctDate.toISOString())

    setHours will set time in your local timezone, but when you display it, it will show the time in UTC. If you just set it as UTC from the beginning, you'll get the result you want.

    EDIT:

    Just be aware that if you are ahead of UTC, your date will be stored as a UTC date from the previous day, so running setUTCHours will not work as intended, changing your date to midnight of the previous day. Therefore, you first need to add the timezone offset to the date.