Search code examples
javascriptdatetimemomentjsutciso8601

How to convert date time from ISO Format to UTC time zone?


I am using moment.js, and I want to convert from ISO Format date time to UTC time zone.

I can convert from local time to UTC+ISOformat, but I am not able to convert ISO format to UTC time zone.

Input:

2018-03-22T00:00:00Z

Expected output:

date should be in UTC time zone. If I calculate the it should be:

22018-03-21T18:30:00Z
  1. First I want to convert into ISO, After that convert into UTC**.

Not able to Converted local date time to ISO then UTC

We can convert into string, But from ISO format can convert or not?

Fox example: I want to convert ISODATE(2018-03-22T00:00:00Z) into UTC time zone.

function toISO(dt) {
  return moment(dt).format("YYYY-MM-DDTHH:mm:ss") + "Z";
}
var date = new Date();
var isoDate= toISO(date)

Direct we can convert

function toISOWithUtc(dt) {
      return moment(dt).utc().format("YYYY-MM-DDTHH:mm:ss") + "Z";
}
var date = new Date();
toISO(date)

Solution

  • Both 2018-03-22T00:00:00Z and 2018-03-21T18:30:00Z already are in UTC.

    Note the Z in the end? This means that the date is in UTC. It's not a hardcoded letter that you can just append to the end - it has a specific meaning, it tells that the date/time is in UTC.

    If you want to convert that UTC date to another timezone (I'm guessing that's what you want), you can use moment.tz:

    // convert UTC 2018-03-22T00:00:00Z to Asia/Kolkata timezone
    moment.tz('2018-03-22T00:00:00Z','Asia/Kolkata')
    

    Just change the timezone name to the one you want to convert.

    And calling format() will give you the converted date/time in ISO8601 format:

    moment.tz('2018-03-22T00:00:00Z','Asia/Kolkata').format() // 2018-03-22T05:30:00+05:30
    

    Note that the offset changed from Z to +05:30. This means that the date/time above is 5 hours and 30 minutes ahead UTC, which is the result of converting 2018-03-22T00:00:00Z to Kolkata's timezone.

    Note: I think you're mistaking the concepts here.

    UTC is a time standard. It defines things like the current date/time accross the world, it uses atomic clocks to make sure everybody on Earth are synchronized, and timezones are all based on offsets from UTC.

    ISO8601 is a standard for exchanging date/time-related data. It defines formats (text representations of dates). A date/time can be in ISO format, regardless of being in UTC or not.

    That's why "convert from UTC to ISO" (or vice-versa) makes no sense at all.