Generating ISO-compliant timestamp strings in Javascript

This Javascript snippet generates an ISO 8601-compliant timestamp string, for example: 2010-04-08T01:38:03.181Z. Very useful for making AJAX calls to ASP.NET websites since you can pass such a string to the System.DateTime.Parse(…) method in the .NET Framework.

function PadZeros(value, desiredStringLength)
{
    var num = value + "";
    while (num.length < desiredStringLength)
    {
        num = "0" + num;
    }
    return num;
}
function ToIsoString(d)
{
return d.getUTCFullYear() + '-' + PadZeros(d.getUTCMonth() + 1, 2) + '-' + PadZeros(d.getUTCDate(), 2) + 'T' + PadZeros(d.getUTCHours(), 2) + ':' + PadZeros(d.getUTCMinutes(), 2) + ':' + PadZeros(d.getUTCSeconds(), 2) + '.' + PadZeros(d.getUTCMilliseconds(), 3) + 'Z';
}

// Example usage:
var myUtcString = ToIsoString(new Date());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s