Mastodon Mastodon - JavaScript ISO date with local timezone
 logo
  • Home 
  • Tags 
  • Blog posts 
  1. Home
  2. Blog posts
  3. JavaScript ISO date with local timezone

JavaScript ISO date with local timezone

Posted on August 18, 2021  (Last modified on July 11, 2024) • 1 min read • 132 words
Javascript   Dev   Solved  
Javascript   Dev   Solved  
Share via

It seems JS has until today no native (!) solution to get an ISO 8601 date & time string in the local time zone (it’s always in UTC). (Super weird, but okay).

I updated the solution on Stackoverflow a bit using “new” ES2017 functionality like this:

function getISOLocalString() {
  let date = new Date();
  let tzo = -date.getTimezoneOffset();

  if (tzo === 0) {

    return date.toISOString();

  } else {

    let dif = tzo >= 0 ? '+' : '-';
    let pad = function(num, digits=2) {
      return String(num).padStart(digits, "0");
    };

    return date.getFullYear() +
      '-' + pad(date.getMonth() + 1) +
      '-' + pad(date.getDate()) +
      'T' + pad(date.getHours()) +
      ':' + pad(date.getMinutes()) +
      ':' + pad(date.getSeconds()) +
      dif + pad(tzo / 60) +
      ':' + pad(tzo % 60) +
      '.' + pad(date.getMilliseconds(), 3);

  }
}

console.log(getISOLocalString());
 Lexoffice API notes
Backup tool evaluation 
In case you want to follow me

Here are some links. The further to the right, the less active.

           
(c) Axel Bock | Powered by Hinode.
Link copied to clipboard
Code copied to clipboard