Get ISO string from a date without time zone

102,042

Solution 1

It's very unclear what you're asking. If you want the UTC date with the hours always 0, then set the UTC hours to 0 and use toISOString, e.g.

var d = new Date();
d.setUTCHours(0,0,0,0);
console.log(d.toISOString());

Of course this is going to show the UTC date, which may be different to the date on the system that generated the Date.

Also,

new Date('2017-04-27').toISOString();

should return 2017-04-27T00:00:00Z (i.e. it should be parsed as UTC according to ECMA-262, which is contrary to ISO 8601 which would treat it as local), however that is not reliable in all implementations in use.

If you just want to get the current date in ISO 8601 format, you can do:

if (!Date.prototype.toISODate) {
  Date.prototype.toISODate = function() {
    return this.getFullYear() + '-' +
           ('0'+ (this.getMonth()+1)).slice(-2) + '-' +
           ('0'+ this.getDate()).slice(-2);
  }
}

console.log(new Date().toISODate());

However, since the built-in toISOString uses UTC this might be confusing. If the UTC date is required, then:

if (!Date.prototype.toUTCDate) {
  Date.prototype.toUTCDate = function() {
    return this.getUTCFullYear() + '-' +
           ('0'+ (this.getUTCMonth()+1)).slice(-2) + '-' +
           ('0'+ this.getUTCDate()).slice(-2);
  }
}

console.log(new Date().toUTCDate());

Solution 2

You can achieve this by simply formating everything that you need in place using moment.format() and then simply append the extra Z to the string. You have to do this as Z within moment JS is reserved for outputting.

var date = moment('2014-08-28').format("YYYY-MM-DDT00:00:00.000") + "Z";

Fiddle example https://jsfiddle.net/2avxxz6q/

Solution 3

old_date = Fri Jan 08 2021 16:01:30 GMT+0900

const new_date = old_date.toISOString().substring(0, 10);

new_date = "2021-01-08"

Solution 4

you can try this, it works for me! you will have the ISO format without timeZone effect

Fri Jan 01 2021 23:10:00 GMT+0100 => 2021-01-01T23:10:00.000Z

function isoDateWithoutTimeZone(date) {
  if (date == null) return date;
  var timestamp = date.getTime() - date.getTimezoneOffset() * 60000;
  var correctDate = new Date(timestamp);
  // correctDate.setUTCHours(0, 0, 0, 0); // uncomment this if you want to remove the time
  return correctDate.toISOString();
}


        var now= new Date("01-01-2021 23:10:00");
        console.log(now.toString());
        var returnedDate = isoDateWithoutTimeZone(now);
        console.log(returnedDate);

Solution 5

You don't need moment.js library, you can just parse and connect date components. For example

type Components = {
  day: number,
  month: number,
  year: number
}

export default class DateFormatter {
  // 2018-11-11T00:00:00
  static ISOStringWithoutTimeZone = (date: Date): string => {
    const components = DateFormatter.format(DateFormatter.components(date))
    return `${components.year}-${components.month}-${components.day}T00:00:00`
  }

  static format = (components: Components) => {
    return {
      day: `${components.day}`.padStart(2, '0'),
      month: `${components.month}`.padStart(2, '0'),
      year: components.year
    }
  }

  static components = (date: Date): Components => {
    return {
      day: date.getDate(),
      month: date.getMonth() + 1,
      year: date.getFullYear()
    }
  }
}
Share:
102,042
Maximus Decimus
Author by

Maximus Decimus

Updated on July 09, 2022

Comments

  • Maximus Decimus
    Maximus Decimus almost 2 years

    My configuration is Lisbon time zone. When I do new Date() I get my current local date/time which is Fri Apr 28 2017 01:10:55 GMT+0100 (GMT Daylight Time)

    When I get the ISO string with toISOString() it will apply the time zone and I will get:

    2017-04-28T00:10:55.964Z
    

    The problem is that some minutes ago the date time was like this (yesterday):

    2017-04-27T23:45:05.654Z
    

    I tried moment.js (new to this) and I did something like this

    document.write(moment('2017-04-28').format())
    

    But I get this 2017-04-28T00:00:00+01:00 which is not 2017-04-28T00:00:00.000Z

    I want to pass this value as a parameter of a restful method to parse it automatically as a DateTime type, but if I pass the output from moment.js format then it will get parsed as 2017-04-27 23:00:00.00

    If I create a new date with new Date() or with new Date('2017-04-27') (date portion), I just want to get the ISO format like as follows with no time zone:

    2017-04-28T00:00:00.000Z
    

    Is there a javascript method like toISOString() or using maybe moment to get that format?

    No matter what time zone or moment of day, I just to simulate that is midnight of the date given.

  • Maximus Decimus
    Maximus Decimus about 7 years
    Thanks for you answer. But it is not The output is 2017-04-27T23:00:00.000Z and I looking 2017-04-28T00:00:00.000Z. Today for me is already April 28 and not April 27.
  • li x
    li x about 7 years
    I updated my answer to include an alternative if your not worried about the time component
  • li x
    li x about 7 years
    Changed it again and tested output here jsfiddle.net/2avxxz6q @MaximusDecimus
  • nmante
    nmante over 6 years
    This helped me. I was looking for the current client side UTC date (without timezone or timestamp).
  • li x
    li x over 4 years
    While you might not need moment, this set of code really looks like it's tending towards remaking the wheel for a 3.2kb gzip I'd still take moment.
  • Yunnosch
    Yunnosch over 3 years
    While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
  • Yunnosch
    Yunnosch over 3 years
    Please discuss especially why you propose exactly the solution discussed in a the most upvoted older existing answer as not reliable. I.e. your contribution is not new and you'd have to point out its advantages in contrast to the current notion that it has disadvantages. There is also another older answer, not upvoted though, which proposes the same as yours, just with at least a linkg to some info. Copying other answers, or reposting them for lack of reading the existing answers, is not appreciated here, because it does not provide additional value to the Q/A collection.
  • Damien Minter
    Damien Minter over 3 years
    Just trying to provide a simple solution here. I didn't have a lot of time and definitely didn't copy and paste it from someone else. If fact there isn't an answer given like mine above, although on reading through again, someone has put something similar in the comments. Feel free to edit this to add an explanation if you have more time than I do, if not I will just leave it here for anyone who might find it useful (and doesn't have a lot of time to read through an explanation of why my solution is better or worse than any of the others)
  • AxeEffect
    AxeEffect over 3 years
    This one liner is clear enough for any JavaScript developer to know what's going on. Simple and effective, it's just removing the unwanted time characters of the date string. I wonder why no one came with this solution before. I cannot see that older answer where this solution is reportedly already answered.
  • AxeEffect
    AxeEffect over 3 years
    However I do agree it needs further styling polish. The first and last lines should be part of the code block. 1st line: const old_date = new Date("Fri Jan 08 2021 16:01:30 GMT+0900");. Last line: console.log(new_date); // "2021-01-08". And, even when the solution is self-explanatory, a 1-line intro would better present the solution.
  • Chris C
    Chris C over 2 years
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
  • Andy
    Andy about 2 years
    @PatrickSzalapski, your "easier" version is not doing the same thing, because your substring will be taken from the UTC instead of the local date and this will be different for some ours a day.
  • Patrick Szalapski
    Patrick Szalapski about 2 years
    Ah yes, of course. Thanks for the catch. I've deleted my comment to avoid confusion.