How to work with Unix Timestamps in JavaScript: A practical guide
While Unix timestamps are not that much cool and relevant to normal people in their day-to-day life, if you ask a developer or programmer about the same, it will be a whole different story altogether.
While a Graphical User Interface (GUI) is excellent for quick checks and validation, it doesn’t work quite the same when you are actively dealing with timestamps (especially Unix timestamps) on a day-to-day basis, and just like any other dev!
Often, you might think, why not build a utility in the first place for the same? How hard can it be?
If you think like that, you’ve come to the right place! This guide will provide a practical walkthrough for working with Unix timestamps in JavaScript from creation and conversion to formatting. We will cover everything required on how to get the current timestamp, convert it into a human-readable date, and parse a date back into a timestamp, all whilst giving you a heads up to avoid common pitfalls, errors, and all those nitty-gritty details that you require to know about timestamps.
Don’t Let Time Confuse You: Conquering Unix Timestamp(s) in JavaScript
The first step in making a conversion is to actually know what we are trying to convert, which in our case is Unix Timestamps.
Unix timestamp is a way to track time as a running total of seconds. It was chosen by an engineer at Bell Labs to represent a convenient and uniform starting point for expressing time, i.e., January 1, 1970, 00:00:00 UTC.
Therefore, the Unix timestamp is nothing but merely the number of seconds that have elapsed between a particular date and the Unix Epoch.
Now you know what a Unix timestamp is. The next step is how do you get the same value in JavaScript. Actually, it’s quite simple. To get the current timestamp in milliseconds in JavaScript, you can use the Date.now() method. This is a static method of the Date object and is the most direct way to get the value.
But what if you want to get the current Unix timestamp in a much more traditional format, let’s say seconds, for instance? Simple, you simply take the result of Date.now() object and divide it by 1000. Since a timestamp must be an integer by all means, you should use Math.floor() to round down to the nearest whole number.
To make it easier for you, the whole syntax would look something like this:
Math.floor(Date.now() / 1000)
Making Dates Human-Friendly: From Timestamp to Readable Text
Now you know what a Unix timestamp is and how to get its value in JavaScript. The next part is to format it into a human-readable format so a normal person like you and me can understand it.
JavaScript offers several built-in methods for this conversion, from simple one-liners to a powerful API for more complex needs.
Let’s get started with the more common ones:
- .toString(): The default and the most used representation for the current time. It displays full date, time, and timezone based on the user’s local system settings. Something like:
Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)
While this method is quite simple to implement, the format can be inconsistent across different browsers and regions.
.toUTCString(): UTC or Coordinated Universal Time is the global standard to regulate clocks and time. In simple words, UTC is the world’s shared time reference, used to make sure clocks are set accurately and consistently everywhere without getting confused.
The .toUTCString() converts the Date() object into the Coordinated Universal Time or UTC format, making time and technology easier for us. The format for UTC is something like this:
Wed, 14 Jun 2017 07:00:00 GMT
This method helps us avoid any ambiguity related to the user’s local timezone by giving a timezone-independent string.
.toLocaleString(): This method, as the name suggests, gives the time according to the specific locale (i.e., language and region). For more customised output, you can pass arguments, making it a more flexible method that formats dates according to a particular language and region.
The format for the same is as follows:
const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
event.toLocaleString("en-GB", { timeZone: "UTC" });
More information regarding the formats used for specific locales can be found here
A new modern standard called Intl.DateTimeFormat can be used for more control over formatting. It allows you to specify the exact timeZone (e.g., “America/New_York”) along with styles for the date and time, saving your time while finding the exact locale for your region.
Date Doctor: Validating Your Dates Before You Make Them Go Viral
After reading around Dates for a few days and feeling the urge to go viral in this ultimate social-driven world, you need to deal with a very common issue while converting and formatting dates in JavaScript.
Invalid Dates can silently wreak havoc in your app and frustrate your users, easily breaking your in-app experience. To avoid this simple yet impactful mistake, you can use a built-in method known as isNaN() on the resulting Date object’s value.
Here is an example for the same:
function isValidDate(dateStr) {
const date = new Date(dateStr);
return !isNaN(date);
}
console.log(isValidDate("2025-11-20")); // true
console.log(isValidDate("invalid-date")); // false
If you are like me and don’t trust the built-in methods that much. A very popular library (not actively maintained) named Moment.js specifically made to be compatible with JavaScript can be used to provide robust date parsing and validation.
While this step seems very simple and easy to implement, most people try to avoid this and end up messing with their dates later. So, validate your dates upfront and help yourselves save time and downstream bugs.
Pro tip: Enhance Validation with Regular Expressions & Libraries
If you are like me and want to go the old school way, this section is for you.
Apart from using libraries and internal functions, there is another way to validate the date format, especially when you’re dealing with particular formats like YYYY-MM-DD or DD/MM/YYYY.
This method uses regular expressions to ensure the format is correct. Here is an example of the same:
const datePattern = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD format
function isValidFormat(dateStr) {
return datePattern.test(dateStr);
}
console.log(isValidFormat("2025-11-20")); // true
console.log(isValidFormat("20-11-2025")); // false, unexpected format
This method can be super helpful when you are dealing with varied Date formats on the same platform. However, this method is just a naive way to do it; for a more robust approach, popular libraries like Moment.js, Day.js, or date-fns can be used to convert different date formats into a much more consistent string. Here is an example of the same:
// Using Moment.js
const moment = require('moment');
function isValidWithMoment(dateStr, format) {
return moment(dateStr, format, true).isValid();
}
console.log(isValidWithMoment("2025-11-20", "YYYY-MM-DD")); // true
console.log(isValidWithMoment("11/20/2025", "YYYY-MM-DD")); // false
These methods work well for basic tasks like checking if a date is valid or making sure all dates follow the same format. But for stronger validation, it’s recommended to combine both client and server-side checks ensuring a more robust validation.
Showing clearer error messages on the frontend so users can understand what exactly went wrong without wondering in the dark.
Also, make sure to handle different time zones carefully (apparently 24 of them) and always make sure the date falls within a sensible range to avoid breaking your app.
Timestamp whisperer: Talking to time in JavaScript
Till this point, we’ve played with JavaScript enough to understand Unix Timestamp is and what to expect out of it.
Now comes the fun part, this section doesn’t tell you something specific but instead lets you dive deep into the relation b/w two of the most quirky elements, i.e., Unix timestamp and JavaScript.
Let’s start with something basic. If you’re in a hurry and don’t want a full-fledged solution to convert a Unix timestamp to a human-readable format, then this 2-line solution will work like wonders for you:
const unixTimestamp = 1651822834; //seconds
const date = new Date(unixTimestamp * 1000);
console.log(date.toString());
// Example output: Fri May 06 2022 15:40:34 GMT 15:40:34 GMT +0000 (UTC)
That was a simple and quick way to see a basic conversion in case you wanted to do that as required.
But if you’re getting hands-on with any technical judging & searching through seconds & time, in real life:
const dateObj = new Date(unixTimestamp * 1000)
const hours = dateObj.getUTCHours();
const minutes = dateObj.getUTCMinutes();
const seconds = dateObj.getUTCSeconds()
const formattedTime = ${hours}: ${minutes}: ${seconds};
console.log(formattedTime)
// Example output: 15:40:34
If you are not a fan of the ‘24-hour format’ and want to convert it into something as simple as “AM” & “PM”, then here is something that can help you:
const formattedTime = date.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: true // this line is the most important one
});
console.log(formattedTime)
// Example output: 12:00 PM
Wrapping Up Time: Master Your Unix Timestamps in JavaScript
To wrap up this comprehensive guide on working with Unix timestamps in JavaScript, it’s clear that while Unix timestamps might seem like arcane numbers to most, they are indispensable tools for developers and programmers who deal with time programmatically every day.
This practical guide has walked you through everything from understanding what Unix timestamps are, how to get the current timestamp in JavaScript, converting those timestamps to human-friendly date formats, and validating your dates to avoid common pitfalls that can trip up even seasoned developers.
Remember, working with timestamps isn’t just about converting numbers to dates. It’s about making time data accurate, consistent, and relevant to your users, regardless of their locale or timezone. Using JavaScript’s built-in methods like Date.now(), .toUTCString(), .toLocaleString(), and the powerful Intl.DateTimeFormat API lets you achieve this with elegance and precision.
Validating your dates early using simple functions or robust libraries like Moment.js ensures your application handles time data securely and reliably, saving you debugging headaches down the line.
Lastly, knowing how to convert Unix timestamps and format them to readable strings, whether it’s quick hacks or deep locale-aware formatting, empowers you to build better user experiences that speak the language of time everyone understands.
If this guide helped you make peace with Unix timestamps in JavaScript, stay tuned for more practical coding insights coming your way here. And if you ever get stuck, remember there are plenty of tools and libraries to lend you a hand—plus this guide to revisit!
Keep coding and don’t let time confuse you!