How to Get, Convert & Format JavaScript Date From Timestamp
By
Community /
Use Cases
Feb 10, 2023
Navigate to:
Have you ever needed to work with dates in JavaScript but struggled to convert timestamps into human-readable dates? Fear not, because in this tutorial, we’ll get, convert, and format JavaScript dates from timestamps.
Getting a date from a timestamp
Before converting a timestamp to a date in JavaScript, we must first obtain the timestamp. Depending on what you’re trying to do, there are a few different ways to get a timestamp in JavaScript. Here are some common ways to get a timestamp.
Using the Date object
The Date object in JavaScript is a built-in object that provides a way to work with dates and times. It represents a specific instant in time and provides methods for getting various components of a date, such as a year, month, day, hour, minute, second, and millisecond.
To create a new Date object, use the “new” keyword followed by the Date constructor, with or without any arguments. The Date object will represent the current date and time if no argument is specified. If an argument is specified, it can be a timestamp (in milliseconds since January 1, 1970), a string date in a specific format, or separate values for year, month, day, hour, minute, second, and millisecond.
Once you have a Date object, you can use various methods to get specific parts of the date and time. For example, you can use the getFullYear() method to get the year, the getDate() method to get the day of the month, the getMonth() method to get the month (0-based), the getHours() method to get the hour, and so on. You can also use set methods to set specific parts of the date and time.
To get the current timestamp, we can create a new Date object and call the getTime() method, which returns the number of milliseconds since January 1, 1970, 00:00:00 Universal Coordinated Time (UTC).
const timestamp = new Date().getTime();
console.log(timestamp); // prints the current timestamp
Using the Date.now() method
Another way to get the current timestamp in JavaScript is by using the Date.now() method. This method returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, just like the getTime() method. Here’s an example:
const timestamp = Date.now();
console.log(timestamp); // prints the current timestamp
The Date.now() method is a built-in function in JavaScript that allows developers to retrieve the current timestamp quickly. Its primary advantage is that it returns the number of milliseconds, rather than seconds or minutes, since January 1, 1970, at midnight UTC.
This specific date and time is known as the Unix Epoch or Unix Time, and it serves as a standard reference point for many computer systems. By counting the number of milliseconds since this reference point, developers are able to calculate accurate time intervals and durations.
In contrast to the getTime() method, which is a function of the Date object, Date.now() is a static method. This means that it is called on the Date class itself rather than on an instance of the Date object. As a result, creating a new Date object is unnecessary before calling the method.
Using Date.now() is typically faster and more efficient than other methods of retrieving the current timestamp in JavaScript, such as new Date().getTime(). Additionally, it’s considered a best practice to use Date.now() when high precision is not required, as it provides an accurate timestamp while avoiding potential issues with time zone offsets and daylight saving time.
Using the Unix timestamp
If you’re working with timestamps from an external source, they may be in Unix timestamp format, representing the number of seconds since January 1, 1970, 00:00:00 UTC. To convert a Unix timestamp to a JavaScript timestamp, we can multiply it by 1,000 to convert it to milliseconds.
const unixTimestamp = 1616608200; // example Unix timestamp
const timestamp = unixTimestamp * 1000;
console.log(timestamp); // prints the corresponding JavaScript timestamp
Converting a timestamp to a date
Now that we have a timestamp, we can convert it to a human-readable date in JavaScript. There are several methods we can use to accomplish this.
Using the Date object
One way to convert a timestamp to a date in JavaScript is by creating a new Date object and passing the timestamp as an argument. Then, we can use the various Date methods to get the individual date components.
const timestamp = 1616608200000; // example timestamp
const date = new Date(timestamp);
console.log(date.getFullYear()); // prints the year (e.g. 2021)
console.log(date.getMonth()); // prints the month (0-11, where 0 = January)
console.log(date.getDate()); // prints the day of the month (1-31)
console.log(date.getHours()); // prints the hour (0-23)
console.log(date.getMinutes()); // prints the minute (0-59)
console.log(date.getSeconds()); // prints the second (0-59)
Using the Intl.DateTimeFormat object
Another way to convert a timestamp to a date in JavaScript is by using the Intl.DateTimeFormat object, which provides a way to format dates and times according to the user’s locale.
const timestamp = 1616608200000; // example timestamp
const date = new Date(timestamp);
const options = { year: 'numeric', month: 'long', day: 'numeric' };
const formattedDate = new Intl.DateTimeFormat('en-US', options).format(date);
console.log(formattedDate); // prints "March 24, 2021"
Formatting dates from a timestamp
Once we have a Date object, we can format it in a specific way before displaying it to the user. Here are some common ways to format dates in JavaScript.
Using the toLocaleDateString() method
The toLocaleDateString() method is a built-in method of the Date object that returns a string representation of the date in the user’s local time zone. We can pass in options to format the string in different ways.
const timestamp = 1616608200000; // example timestamp
const date = new Date(timestamp);
const formattedDate = date.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(formattedDate); // prints "Wednesday, March 24, 2021"
Using a library
Formatting dates can sometimes be complex. The reason is that different countries or regions have different date formats and time zones. For example, in the United States, the standard date format is month/day/year, whereas in Europe, the standard format is day/month/year. Additionally, some countries use a 12-hour clock, while others use a 24-hour clock.
Moment.js simplifies dealing with these differences by providing various tools to manipulate, validate, and format dates. In addition to formatting dates for multiple regions and time zones, Moment.js can perform complex operations such as computing differences between dates, parsing dates from strings, and manipulating dates with different calendar systems.
To use Moment.js, we first need to install it via a package manager such as npm or yarn. Once installed, we can use its API to format dates in various ways.
const moment = require('moment');
const timestamp = 1616608200000; // example timestamp
const formattedDate = moment(timestamp).format('dddd, MMMM Do YYYY');
console.log(formattedDate); // prints "Wednesday, March 24th 2021"
The API provides a wide range of formatting options, such as converting a date to a human-readable string with the day of the week, month, year, and time. It can also format dates for use in databases or other systems, such as converting milliseconds to a date object or string.
As you can see, Moment.js is a powerful tool. It can make working with dates in JavaScript much easier and more efficient. This is especially useful for web applications that need to display dates in different time zones or regions.
Conclusion
In this tutorial, we covered several topics related to timestamps in JavaScript. Firstly, we discussed various methods for obtaining a timestamp. Additionally, we explored two options for converting timestamps into human-readable dates: the Date object and the Intl.DateTimeFormat object. Finally, we reviewed how to format dates in multiple ways, including through the use of the toLocaleDateString() method or a library like Moment.js. Overall, this tutorial provided a comprehensive introduction to working with timestamps and dates in JavaScript.
Working with dates in JavaScript can be daunting, but with the right tools and techniques, it doesn’t have to be. Understanding how to get, convert, and format dates in JavaScript allows you to build more robust and user-friendly applications that easily handle dates.
About the author:
This post was written by Juan Reyes. As an entrepreneur, skilled engineer, and mental health champion, Juan pursues sustainable self-growth, embodying leadership, wit, and passion. With over 15 years of experience in the tech industry, Juan has had the opportunity to work with some of the most prominent players in mobile development, web development, and e-commerce in Japan and the US.