Skip to content Skip to sidebar Skip to footer

Converting Domtimestamp To Localized Hh:mm:ss Mm-dd-yy Via Javascript

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

Solution 1:

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 = newDate(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 = newDate(domTimeStamp);
var hours = d.getHours(),
    minutes = d.getMinutes(),
    seconds = d.getSeconds(),
    month = d.getMonth() + 1,
    day = d.getDate(),
    year = d.getFullYear() % 100;

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

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

document.write(formattedDate);

Solution 2:

var d = newDate(millisecondsSinceEpoch);

You can then format it however you like.

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

Post a Comment for "Converting Domtimestamp To Localized Hh:mm:ss Mm-dd-yy Via Javascript"