Tuesday, October 13, 2009

Generating RFC 3339 or ISO 8601 Timestamps in JavaScript

I've been working on a generator for a custom Atom 1.0 feed. The Atom 1.0 specification (RFC 4287) requires Internet Timestamps (RFC 3339) which are based on ISO 8601 but these are not supported by the JavaScript Date object. Failing to find a drop-in JavaScript snippet which could generate the necessary timestamp format, I created the following function. It generates the Internet timestamp string from either the current time or a JavasScript Date object passed as an argument.

/*
Internet Timestamp Generator
Copyright (c) 2009 Sebastiaan Deckers
License: GNU General Public License version 3 or later
*/
var timestamp: function (date) {
var pad = function (amount, width) {
var padding = "";
while (padding.length < width - 1 && amount < Math.pow(10, width - padding.length - 1))
padding += "0";
return padding + amount.toString();
}
date = date ? date : new Date();
var offset = date.getTimezoneOffset();
return pad(date.getFullYear(), 4)
+ "-" + pad(date.getMonth() + 1, 2)
+ "-" + pad(date.getDate(), 2)
+ "T" + pad(date.getHours(), 2)
+ ":" + pad(date.getMinutes(), 2)
+ ":" + pad(date.getSeconds(), 2)
+ "." + pad(date.getMilliseconds(), 3)
+ (offset > 0 ? "-" : "+")
+ pad(Math.floor(Math.abs(offset) / 60), 2)
+ ":" + pad(Math.abs(offset) % 60, 2);
}


Examples:
timestamp();
// "2009-10-13T13:34:52.000+02:00"

timestamp(new Date(1983, 4, 9, 11, 5, 17));
// "1983-05-09T11:05:17.000+02:00"


Hope this helps anyone.

4 comments:

Test said...

Thanks!

I will use it in my Chrome extension (sync with Opera Link).

avl555 said...

This is the extension:
https://github.com/aykevl93/Chrome-Sync
It synchronizes Google Chrome with Google Bookmarks and Opera Link, but it is not complete yet (for example, it lacks a good user interface...)

ngochaucr said...

I get RFC Timestamp from get event list of google calendar
how to convert UTC Timestamp?

MyHelpful Scripts said...

Hi Sebastiaan,

I have used your work for a Gmail Reminder script I wrote. If you want to, you can view it here: http://www.myhelpfulscripts.com/email-reminder-with-tasks/

Please let me know if you want me to credit you differently.

Thanks again for your awesome work!