Converting dates returned from database to UTC within ASP pages

1 minute read time.

When answering a customer's question about formatting dates in an ASP page to UTC, I created a couple of useful functions.

The customer needed to retrieve dates from the communication record in preparation for sending to an external scheduling system.

var commRecord = CRM.FindRecord("communication","comm_communicationid="+intRecordId);
var createddate = commRecord.ItemAsString("comm_createddate");
var startdatetime = commRecord.ItemAsString("comm_datetime");
var enddatetime = commRecord.ItemAsString("comm_todatetime");

Using the method itemAsString() to return the field's value from the record gave me a baseline.

function padNumber(num) {
    return (num < 10 ? "0" : "") + num;
}

function convertToUTCDate(dateString) {
    // Split date and time
    var parts = dateString.split(" ");
    var dateParts = parts[0].split("/");
    var timeParts = parts[1].split(":");

    // Extract components
    var day = parseInt(dateParts[0], 10);
    var month = parseInt(dateParts[1], 10) - 1; // JS months are 0-based
    var year = parseInt(dateParts[2], 10);
    var hours = parseInt(timeParts[0], 10);
    var minutes = parseInt(timeParts[1], 10);

    // Create local date object
    var localDate = new Date(year, month, day, hours, minutes, 0);

    // Convert to UTC
    var utcYear = localDate.getUTCFullYear();
    var utcMonth = padNumber(localDate.getUTCMonth() + 1);
    var utcDay = padNumber(localDate.getUTCDate());
    var utcHours = padNumber(localDate.getUTCHours());
    var utcMinutes = padNumber(localDate.getUTCMinutes());
    var utcSeconds = "00"; // ICS format includes seconds

    // Return UTC format
    return utcYear + utcMonth + utcDay + "T" + utcHours + utcMinutes + utcSeconds + "Z";
}

The padNumber() function manually pads numbers below 10.

The function can then be used like this:

Response.Write("Created Date Time ="+convertToICSDate(createddate)+"\r\n");
Response.Write("Start Date Time ="+convertToICSDate(startdatetime)+"\r\n");
Response.Write("End Date Time = "+convertToICSDate(enddatetime)+"\r\n");

I hope you find this useful.