Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Goal: Find the local time and UTC time offset then construct the URL in following format.

Example URL: /Actions/Sleep?duration=2002-10-10T12:00:00?05:00

The format is based on the W3C recommendation: http://www.w3.org/TR/xmlschema11-2/#dateTime

The documentation says:

For example, 2002-10-10T12:00:00?05:00 (noon on 10 October 2002, Central Daylight Savings Time as well as Eastern Standard Time in the U.S.) is equal to 2002-10-10T17:00:00Z, five hours later than 2002-10-10T12:00:00Z.

So based on my understanding, I need to find my local time by new Date() then use getTimezoneOffset() function to compute the difference then attach it to the end of string.

1.Get local time with format

var local = new Date().format("yyyy-MM-ddThh:mm:ss"); //today (local time)

output

2013-07-02T09:00:00

2.Get UTC time offset by hour

var offset = local.getTimezoneOffset() / 60;

output

7

3.Construct URL (time part only)

var duration = local + "-" + offset + ":00";

output:

2013-07-02T09:00:00-7:00

The above output means my local time is 2013/07/02 9am and difference from UTC is 7 hours (UTC is 7 hours ahead of local time)

So far it seems to work but what if getTimezoneOffset() returns negative value like -120?

I'm wondering how the format should look like in such case because I cannot figure out from W3C document. Thanks in advance.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The below should work properly, and for all browsers (thanks to @MattJohnson for the tip)

function toIsoString(date) {
  var tzo = -date.getTimezoneOffset(),
      dif = tzo >= 0 ? '+' : '-',
      pad = function(num) {
          var norm = Math.floor(Math.abs(num));
          return (norm < 10 ? '0' : '') + norm;
      };

  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);
}

var dt = new Date();
console.log(toIsoString(dt));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...