NOTE: This was written back in 2007 discussing code written even earlier. This code is different than Date.toISOString() in at least two major respects:

  1. It prints local time instead of UTC time.
  2. It uses "+00:00" instead of "Z" (Zulu time) for UTC.

A couple of years ago I had to print dates in JavaScript in UTC (ISO-8601) format (yyyy-MM-ddTHH:mm:ss.fff[+-]ZZ:ZZ). Here is the function that I developed. It assumes the date object has the correct time zone offset and uses the time zone offset from the object.

I also developed server-side C# code for formatting dates in ASP.NET pages which I'll post soon.

function pad(value, digits, padtext) {
  if (!padtext) padtext = "00000000";
  if ((digits == null) || (typeof(digits) == "undefined")) return value;
  if ((value == null) || (typeof(value) == "undefined")) return value;
  var length = value.toString().length;
  if ((length < digits) && (digits < padtext.length))
    return padtext.substr(0, digits - length) + value.toString();
  else
    return value;
}

function toUTCDateTime(date) {
  var tz = date.getTimezoneOffset();
  var offset = ((tz <= 0) ? "+" : "-");
  tz = Math.abs(tz);
  offset += pad(Math.floor(tz / 60), 2) + ":" + pad(tz % 60, 2);

  var result = date.getFullYear() + "-" +
    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;

  return result;
}

Comment Section

Comments are closed.