views:

21

answers:

2

The W3C Geolocation API (among others) uses DOMTimeStamp for its time-of-fix.

This is "milliseconds since the start of the Unix Epoch".

What's the easiest way to convert this into a human readable format and adjust for the local timezone?

+1  A: 
var d = new Date(millisecondsSinceEpoch);

You can then format it however you like.

You may find datejs, particularly its toString formatting, helpful.

Matthew Flaschen
+1  A: 

One version of the Date constructor takes the number of "milliseconds since the start of the Unix Epoch" as its first and only parameter.

Assuming your timestamp is in a variable called domTimeStamp, the following code will convert this timestamp to local time (assuming the user has the correct date and timezone set on her/his machine) and print a human-readable version of the date:

var d = new Date(domTimeStamp);
document.write(d.toLocaleString());

Other built-in date-formatting methods include:

Date.toDateString()
Date.toLocaleDateString()
Date.toLocaleTimeString()
Date.toString()
Date.toTimeString()
Date.toUTCString()

Assuming your requirement is to print the exact pattern of "HH:MM:SS MM-DD-YY", you could do something like this:

var d = new Date(domTimeStamp);
var hours = d.getHours(),
    minutes = d.getMinutes(),
    seconds = d.getSeconds(),
    month = d.getMonth() + 1,
    day = d.getDate(),
    year = d.getFullYear() % 100;

function pad(d) {
    return (d < 10 ? "0" : "") + d;
}

var formattedDate = pad(hours) + ":"
                  + pad(minutes) + ":"
                  + pad(seconds) + " "
                  + pad(month) + "-"
                  + pad(day) + "-"
                  + pad(year);

document.write(formattedDate);
Christopher Parker