Skip to content

Instantly share code, notes, and snippets.

@musubu
Created March 24, 2012 07:09
Show Gist options
  • Save musubu/2179331 to your computer and use it in GitHub Desktop.
Save musubu/2179331 to your computer and use it in GitHub Desktop.
convert date to utc isostring format
var dates = ['2003-12-13T18:30:02Z'
, '2003-12-13T18:30:02.25Z'
, '2003-12-13T18:30:02+01:00'
, '2003-12-13T18:30:02.25+01:00'
, '1980'
, 'invalid'
, null
]
function toISOString (string, callback) {
try {
if (new Date(string) == 'Invalid Date') {
callback('1900-01-01T00:00:00.000Z');
} else {
callback((new Date(string)).toISOString());
}
} catch (err) {
callback('1900-01-01T00:00:00.000Z');
}
}
dates.forEach(function(d) {
toISOString(d, function(r) {
console.log(d);
console.log(r + '\n');
})
})
// 2003-12-13T18:30:02Z
// 2003-12-13T18:30:02.000Z
//
// 2003-12-13T18:30:02.25Z
// 2003-12-13T18:30:02.250Z
//
// 2003-12-13T18:30:02+01:00
// 2003-12-13T17:30:02.000Z
//
// 2003-12-13T18:30:02.25+01:00
// 2003-12-13T17:30:02.250Z
//
// 1980
// 1980-01-01T00:00:00.000Z
//
// invalid
// 1900-01-01T00:00:00.000Z
//
// null
// 1970-01-01T00:00:00.000Z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment