Explain Codes LogoExplain Codes Logo

Converting milliseconds to a date (jQuery/JavaScript)

javascript
date-formatting
javascript-libraries
locale
Alex KataevbyAlex Kataev·Sep 28, 2024
TLDR

To transform milliseconds to a date in JavaScript, call the new Date(milliseconds) method like so:

let ms = 1575909015000; console.log(new Date(ms).toLocaleString()); // "12/9/2019, 10:30:15 AM"

This presents a locale-formatted date and time, commencing from the JavaScript-standard epoch (1st January, 1970).

Deciphering the date object

To dissect a date object into its components:

let date = new Date(ms); console.log(date.getFullYear()); // "2019" Hope I looked good in photos! console.log(date.getMonth() + 1); // "12" *Ahem* Remember, month starts at 0. console.log(date.getDate()); // "9" On this day... console.log(date.toDateString()); // "Mon Dec 09 2019" Weekday included for a party plan.

Localizing the dates in your favor

Emphasizing locale and timezone, toLocaleString() is a lifesaver:

console.log(date.toLocaleString("en-US", { timeZone: "America/New_York" })); // "12/9/2019, 5:30:15 AM" Quite early, in the "Big Apple".

Adjust to suit locale formats:

console.log(date.toLocaleString("en-GB")); // "09/12/2019, 10:30:15" Brits like their dates reversed!

Easy date formatting with third-party libraries

When basic functionality won't suffice, libraries like Moment.js or Day.js can help:

// With Moment.js console.log(moment(ms).format("DD/MM/YYYY HH:mm:ss")); // "09/12/2019 10:30:15" In moments, we made it!

Custom date formatting to your rescue

In need of custom formatting? Create your formatter:

function customFormat(date) { let dd = date.getDate(); let mm = date.getMonth() + 1; // January is 0! *winks* let yyyy = date.getFullYear(); // Single digit days and months feel left out. So, they get a 0 pal! dd = dd < 10 ? '0' + dd : dd; mm = mm < 10 ? '0' + mm : mm; return `${dd}/${mm}/${yyyy}`; } console.log(customFormat(new Date(ms))); // "09/12/2019"

Formatting dates: Putting user first

Different users, different formats. Add options to keep everyone happy:

function userPreferredDateFormat(date, format) { // An example implementation with day.js return dayjs(date).format(format); } console.log(userPreferredDateFormat(new Date(ms), "YYYY-MM-DD")); // "2019-12-09" And they lived happily ever after!

Advance moves: Time traveling

Ever wished to add or subtract time? Here you go:

let tomorrowMs = ms + (24 * 60 * 60 * 1000); console.log(new Date(tomorrowMs).toLocaleDateString()); // "12/10/2019" Welcome, tomorrow!

Tackling tricky edge cases

Sometimes, edge cases aren't so edgy. Be wary of leap seconds, time zone deviations, and browser quirks.

Displaying the date: All eyes on this

Finally, don't let your efforts go unnoticed:

document.body.textContent = new Date(ms).toString(); // "That's one small step for man, one giant leap for mankind."