moment.js is great but sometimes you don't want to pull a large number of dependencies for simple things.

The following works as well:

    var tzoffset = (new Date()).getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(Date.now() - tzoffset)).toISOString().slice(0, -1);
    
    console.log(localISOTime)  // => '2015-01-26T06:40:36.181'

The slice(0, -1) gets rid of the trailing Z which represents Zulu timezone and can be replaced by your own.

Answer from yegodz on Stack Overflow
🌐
DEV Community
dev.to › shubhampatilsd › removing-timezones-from-dates-in-javascript-46ah
Removing Timezones from Dates in Javascript - DEV Community
April 23, 2023 - Now, despite the timezone information still being there in the console.log, if we run the same code in Honolulu, we'll get · Wed Feb 22 2023 16:30:00 GMT-1000 (Hawaiian Aleutian Time) The two dates line up! Now here is the actual implementation for the pseudocode: export const dateWithoutTimezone = (date: Date) => { const tzoffset = date.getTimezoneOffset() * 60000; //offset in milliseconds const withoutTimezone = new Date(date.valueOf() - tzoffset) .toISOString() .slice(0, -1); return withoutTimezone; }; First tzoffset initializes a new Date and get the timezone offset in milliseconds (in my case, it would be 28800000 milliseconds).
🌐
GitHub
gist.github.com › lvl99 › af20ee34f0c6e3984b29e8f0f794a319
Date ISO string without timezone information · GitHub
Date ISO string without timezone information · Raw · date-iso-string-without-timezone.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
W3Schools
w3schools.com › jsref › jsref_toisostring.asp
JavaScript Date toISOString() Method
The toISOString() method returns a date object as a string, using the ISO standard.
🌐
MSR
rajamsr.com › home › the best way to convert javascript date to iso string
The Best Way to Convert JavaScript Date to ISO String | MSR - Web Dev Simplified
February 24, 2024 - The code snippet creates a Date object representing the current date and time and then converts it to an ISO string using the toISOString() method. The resulting ISO string will include both date and time components.
🌐
Bobby Hadz
bobbyhadz.com › blog › javascript-create-date-without-timezone
How to Create a Date without Timezone in JavaScript | bobbyhadz
March 6, 2024 - To create a date without timezone: Get the ISO representation of the date string. Remove the Z character from the end of the ISO string. Pass the result to the Date() constructor. index.js · Copied!const dateStr = '2022-07-21T09:35:31.820Z'; ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date › toISOString
Date.prototype.toISOString() - JavaScript - MDN - Mozilla
The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always ...
🌐
GitHub
gist.github.com › barbietunnie › 67d10b59f7716e3ff5892d70dd9a3cfa
Format JS Date in ISO-8601 without timezone issues · GitHub
The following function provides an easy way to format Javascript dates in ISO-8601 format without using date.toISOString(), which could lead to timezone issues as the date is first converted to UTC which could lead to discrepancies in the result in certain timezones.
Find elsewhere
🌐
UsefulAngle
usefulangle.com › post › 30 › javascript-get-date-time-with-offset-hours-minutes
How to get DateTime with Timezone Offset (8601 format) in Javascript
Javascript has a toISOString method that gives a datetime in ISO-8601 format. But it gives datetime strings only in UTC format, YYYY-MM-DDTHH:mm:ss.sssZ. It does not give a timezone offset in hours and minutes.
🌐
GitHub
github.com › moment › moment › issues › 4511
[BUG] toISOString don't return timestamp in UTC · Issue #4511 · moment/moment
December 27, 2017 - Hi all, I have some trouble with the toISOString() method. I want to get the UTC of date but the toISOString() method return my local timezone (GMT +1). This moment("2018-03-23").toISOString() should return 2018-03-23T00:00:00.000Z but when i try it i have 2018-03-22T23:00:00.000Z.
Author   workfel
🌐
GitHub
github.com › date-fns › date-fns › issues › 2151
formatISO doesn't use UTC (Z) timezone · Issue #2151 · date-fns/date-fns
January 12, 2021 - When making a sanity check of now.toISOString() === formatISO(now) (with const now = new Date()), it fails due to a timezone difference, as the formatISO doesn't match the browser's toISOString, which explicitly claims that The timezone is always ...
Author   scscgit
🌐
Spiceworks Community
community.spiceworks.com › programming & development
I do I get Local time using Date().toISOstring() - Programming & Development - Spiceworks Community
February 1, 2017 - I want to extract current localtime. by using the below code, I get incorrect time var t=new Date(); console.log(t.toISOString());
🌐
GitHub
gist.github.com › peterbraden › 752376
toISOString with timezone support · GitHub
December 3, 2013 - Doesn't work well for timezones ahead of zulu. I.e. tz < 0.
🌐
Reality Ripple
udn.realityripple.com › docs › Web › JavaScript › Reference › Global_Objects › Date › toISOString
Date.prototype.toISOString() - JavaScript
if (!Date.prototype.toISOString) { (function() { function pad(number) { if (number < 10) { return '0' + number; } return number; } Date.prototype.toISOString = function() { return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; })(); }
Top answer
1 of 2
8

Based on the polyfill for Date.prototype.toISOString found at MDN's Date.prototye.toISOString:

if (!Date.prototype.toLocalISOString) {
  (function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toLocalISOString = function() {
      return this.getFullYear() +
        '-' + pad(this.getMonth() + 1) +
        '-' + pad(this.getDate()) +
        'T' + pad(this.getHours()) +
        ':' + pad(this.getMinutes()) +
        ':' + pad(this.getSeconds()) +
        '.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        'Z';
    };

  }());
}

So just use this toLocalISOString instead of toISOString.

2 of 2
0

Your Javascript statements are producing the expected results. Tue May 26 2015 14:00:00 GMT+0100 is the same time as 2015-05-26T13:00:00.000Z. Unless you care about a fraction of a second, GMT, UTC, and Z all mean the same thing: mean solar time at 0° longitude, and keeping the same time all year (no change in summer; Iceland observes this time all year). "GMT+0100" means a time zone that is one hour later than 0° longitude, such the United Kingdom in summer. So at a given moment the time in Iceland is 2015-05-26T13:00:00.000Z and also Tue May 26 2015 14:00:00 GMT+0100 in London. Could you clarify what result you want to see? Perhaps you would like "2015-05-26T14:00:00" which is the ISO 8601 notation for some unspecified local time, presumably the local time of the computer displaying the Javascript. Or maybe you want "2015-05-26T14:00:00+01:00", which is ISO 8601 notation for the local time zone one hour ahead of 0° longitude, such as London in summer or Paris in winter.

Building on souldreamer's example, making it fully working and providing the local time offset:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<body>
<pre>
<script language="JavaScript">
    if (!Date.prototype.toLocalISOString) {
        // Anonymous self-invoking function
        (function () {

            function pad(number) {
                if (number < 10) {
                    return '0' + number;
                }
                return number;
            }

            Date.prototype.toLocalISOString = function () {
                timestamp = this.getFullYear() +
                  '-' + pad(this.getMonth() + 1) +
                  '-' + pad(this.getDate()) +
                  'T' + pad(this.getHours()) +
                  ':' + pad(this.getMinutes()) +
                  ':' + pad(this.getSeconds());
                if (this.getTimezoneOffset() == 0) { timestamp = timestamp + "Z" }
                else {
                    if (this.getTimezoneOffset() < 0) { timestamp = timestamp + "+" }
                    else { timestamp = timestamp + "-" }
                    timestamp = timestamp + pad(Math.abs(this.getTimezoneOffset() / 60).toFixed(0));
                    timestamp = timestamp + ":" + pad(Math.abs(this.getTimezoneOffset() % 60).toFixed(0));
                }
                return timestamp;
            };

        }());
    }
    now = new Date();
    document.writeln("Create date object containing present time and print UTC version.");
    document.writeln(now.toUTCString());
    document.writeln("Show local time version");
    document.writeln(now.toLocalISOString());
</script>
</pre>
🌐
W3cubDocs
docs.w3cub.com › javascript › global_objects › date › toisostring
Date.toISOString - JavaScript - W3cubDocs
The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO …