'Anil' Radhakrishna's Code Gallery

Home | Blog | Contact
Show UTC Date/Time recorded on the server IN a user's regional time zone format using Javascript.

This code sample demonstrates how UTC Date/Time recorded on the server can be shown in a user's regional time zone format with just Javascript.

I cooked up this Javascript function to convert a UTC Date/Time into the visitor's local DateTime format.
function showAsLocalDateTime(utcDateTime){
var localDateTime = new Date(utcDateTime);
return localDateTime.toLocaleString();

It uses Date.parseString (to convert a DateTime string to a Date object) & Date.add (to add or subtract specific elements of a Date) functions from Matt Kruse's Date library.

The table below has 2 columns. Each row in both columns actually contains the same values, a typical UTC (Coordinated Universal Time) DateTime value generated in C# by DateTime.Now.ToUniversalTime()) that looks like this - 2007-09-05 09:37:56. The column on the right (shown in red) has been doctored to show the Date-Time in the user's regional settings.

To do this date formatting, all the cells of the second column are identified with a class name 'local'. The local CSS class is defined thus:
.local { color: red;}

The Javascript function convertUTCDatesToLocalDateTime() is called in the window OnLoad event.

function convertUTCDatesToLocalDateTime()
if (document.getElementsByTagName('td')){
 for (var i = 0; (cell = document.getElementsByTagName('td')[i]); i++){
	if (cell.className == 'local'){
		cell.innerHTML = 
		showAsLocalDateTime(Date.parseString(cell.innerHTML,"yyyy-MM-dd hh:mm:ss"));

It picks each cell marked with the class name 'local' & dynamically replaces the content of it so that when the page finishes loading what you see is the DateTime in the user's regional time zone format rather than the UTC Date/Time that it actually contains!

(Choose View > Source from the browser menu to view complete code)

This trick can be adapted for ASP.NET pages as well.
2007-09-05 09:37:56 2007-09-05 09:37:56
2007-09-06 09:37:56 2007-09-06 09:37:56
2007-09-04 09:37:56 2007-09-04 09:37:56