Goal: Find the local time
and UTC time offset
, and then construct the URL in the following format.
Example URL:/Actions/Sleep?duration=2002-10-10T12:00:00−05:00
This format is based on W3C recommendations. The documentation says:
For example, 2002-10-10T12:00:00−05:00 (at noon on October 10, 2002, Central Daylight Time and Eastern Standard Time) Equal to 2002-10-10T17:00:00Z, which is five hours later than 2002-10-10T12:00:00Z.
So from my understanding I need to find the local time via new Date()
and then calculate the difference using the getTimezoneOffset()
function and then append it to the end of the string .
Use format
to get the local time
var local = new Date().format("yyyy-MM-ddThh:mm:ss"); // 2013-07-02T09:00:00
Get UTC time offset
var offset = local.getTimezoneOffset() / 60; // 7
Construct URL (time part only)
var duration = local + "-" + offset + ":00"; // 2013-07-02T09:00:00-7:00
The above output means that my local time is 9am on July 2, 2013, which is 7 hours different from UTC (UTC is 7 hours ahead of local time)
So far it seems to work, but what if getTimezoneOffset()
returns a negative value (e.g. -120)?
I'm wondering what the format should look like in this case, since I can't figure it out from the W3C documentation.
getTimezoneOffset()
Returns the opposite sign of the format required by the specification you reference.This format is also known as ISO8601, or more accurately RFC3339.
In this format, UTC is represented by
Z
, while all other formats are represented by an offset from UTC. The meaning is the same as in JavaScript, but the order of subtraction is reversed, so the result has the opposite sign.Additionally, there is no method named
format
on the localDate
object, so the function in #1 will fail unless you use a library for this purpose. See this document.If you are looking for a library that can work with this format directly, I recommend trying moment.js. In fact, this is the default format, so you can simply do:
This is a well-tested cross-browser solution and has many other useful features.
This is a simple helper function that formats JS dates for you.