How to Convert Unix Timestamp to Date in JavaScript

Moataz Farid Feb 12, 2024
  1. How to Convert Timestamp to Date in JavaScript Using the Date Class
  2. How to Convert Timestamp to Date in JavaScript Using the Intl.DateTimeFormat Method
  3. How to Convert Timestamp to Date in JavaScript Using the toLocaleString() Method
  4. How to Convert Timestamp to Date in JavaScript Using Moment.js
  5. JavaScript Convert Timestamp to Date FAQ
  6. How to Convert Timestamp to Date in JavaScript Conclusion
How to Convert Unix Timestamp to Date in JavaScript

This tutorial will explain how we can convert the Unix timestamp to date in JavaScript. Unix timestamp is the time elapsed since the 1, Jan 1970 00:00:00 UTC, represented in seconds.

The JavaScript Date object contains the representation for the time elapsed since the 1, Jan 1970 00:00:00 UTC in milliseconds.

How to Convert Timestamp to Date in JavaScript Using the Date Class

In JavaScript, the Date class provides a powerful set of various date methods and properties to work with dates and times.

Creating a new object from the Date class using new Date() returns the current new JavaScript date object, which has the current date and time, with the value represented in milliseconds since the Unix epoch.

However, to obtain the proper Date object that corresponds to a specific Unix timestamp, we can pass the timestamp (in milliseconds) as an argument to the Date constructor.

Code Input:

var timestamp = 1607110465663
var date = new Date(timestamp);
console.log(date.getTime())
console.log(date)

Code Output:

convert timestamp to date - output 1

In this example, the timestamp variable holds a Unix timestamp (in milliseconds) that corresponds to December 4, 2020, 19:34:25.663 UTC. By creating a new Date object with this timestamp, we are effectively converting the timestamp value into a human-readable date and time representation.

The Date class provides many methods to represent the Date in the preferred format.

getDate() Returns the day of the calendar month 1 to 31 at that time.
getMonth() Returns the month number 0 to 11 at that time.
getFullYear() Returns the year in 4-digits format.
getHours() Returns the exact hour in 24-hour format for that time.
getMinutes() Returns the exact minutes 0 to 59 at that time.
getSeconds() Returns the exact seconds 0 to 59 at that time.

Code Input:

var timestamp = 1607110465663
var date = new Date(timestamp);

console.log(
    'Date: ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' +
    date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' +
    date.getSeconds());

Code Output:

convert timestamp to date - output 2

Since the JavaScript Date timestamp is in the unit of millisecond while the Unix timestamp is in the unit of second, we can multiply 1000 to convert the Unix timestamp to the JavaScript timestamp. If the Unix timestamp is 1607110465, then the JavaScript timestamp is 1607110465000.

The following example demonstrates how we can convert the Unix timestamp to a JavaScript Date timestamp.

Code Input:

var unixTimestamp = 1693897034
var date = new Date(unixTimestamp * 1000);
console.log('Unix Timestamp:', unixTimestamp)
console.log('Date Timestamp:', date.getTime())
console.log(date)
console.log(
    'Date: ' + date.getDate() + '/' + (date.getMonth() + 1) + '/' +
    date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' +
    date.getSeconds());

Code Output:

convert timestamp to date - output 3

How to Convert Timestamp to Date in JavaScript Using the Intl.DateTimeFormat Method

JavaScript’s Intl.DateTimeFormat object provides powerful capabilities for formatting date and time values according to specific locales and preferences.

This object allows you to create customized date and time representations while considering cultural and regional differences in formatting.

Converting Unix Timestamp to Localized Date

To convert a Unix timestamp to a localized date and time format, you can use the Intl.DateTimeFormat object. This object takes the locale and options as parameters to generate a formatted date string.

Below is an example code that demonstrates how you can achieve this.

Code Input:

// Unix timestamp in seconds
const unixTimestamp = 1693897034;

// Create a Date object from the timestamp
const date = new Date(unixTimestamp * 1000);

// Specify the locale and formatting options
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  timeZoneName: 'short'
};
const formatter = new Intl.DateTimeFormat('en-US', options);

// Format the date
const formattedDate = formatter.format(date);

console.log(formattedDate);

Code Output:

convert timestamp to date - output 4

In this example, we convert the Unix timestamp to milliseconds by multiplying it with 1000 to match the JavaScript timestamp format.

We then create a Date object from this timestamp.

Next, we define the formatting options using the options object, which specifies how we want the date and time to be displayed.

Finally, we create an Intl.DateTimeFormat object with the desired locale and formatting options and use it to format the date and time.

How to Convert Timestamp to Date in JavaScript Using the toLocaleString() Method

The toLocaleString() method is a built-in function in JavaScript that allows you to convert a Date object into a human-readable string representation based on the current locale and formatting preferences.

To convert a Unix timestamp to a localized date and time format, you can follow these steps:

Step 1: Create a Date Object From the Unix Timestamp

Step 2: Use the toLocaleString() Method to Convert the Date Object Into a Formatted String

Below is an example code that demonstrates this method.

Code Input:

// Unix timestamp in seconds
const unixTimestamp = 1693897034;

// Create a Date object from the timestamp
const date = new Date(unixTimestamp * 1000);

// Convert to localized date and time string
const formattedDate = date.toLocaleString();

console.log(formattedDate);

Code Output:

convert timestamp to date - output 5

In this example, we first convert the Unix timestamp to milliseconds by multiplying it by 1000 to match the JavaScript timestamp format. We then create a Date object from this timestamp. Finally, we use the toLocaleString() method without any arguments to convert the Date object into a localized date and time string.

The toLocaleString() method also provides options to customize the formatting of the output. You can pass an options object as an argument to tailor the date and time representation according to your preferences.

// Unix timestamp in seconds
const unixTimestamp = 1693897034;

// Create a Date object from the timestamp
const date = new Date(unixTimestamp * 1000);

// Specify formatting options
const options = {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  timeZoneName: 'short'
};

// Convert to localized date and time string with custom options
const formattedDate = date.toLocaleString('en-US', options);

console.log(formattedDate);

Code Output:

convert timestamp to date - output 7

In this example, we define the options object to specify the desired formatting of the date and time. The toLocaleString() method now takes two arguments: the locale (in this case, en-US) and the formatting options.

The resulting string will adhere to the specified format.

How to Convert Timestamp to Date in JavaScript Using Moment.js

Moment.js is a popular JavaScript library for handling dates and times. It offers a wide range of functionalities, such as parsing, formatting, manipulating, and displaying dates and times.

While Moment.js is no longer actively maintained as of September 2020, it remains a widely used library for projects that require advanced date and time operations.

To convert a Unix timestamp to a human-readable date and time format using Moment.js, follow these steps:

Step 1: Installing Moment.js

To include Moment.js in your project, you can either download the library from the official website or use a package manager like npm or yarn:

npm install moment

Step 2: Converting Unix Timestamp

Once Moment.js is included in your project, you can start using it to convert Unix timestamps:

Code Input:

// Import Moment.js
const moment = require('moment');

// Unix timestamp in seconds
const unixTimestamp = 1693897034;

// Create a Moment object from the timestamp
const momentObject = moment.unix(unixTimestamp);

// Convert to formatted date and time string
const formattedDate = momentObject.format('MMMM Do YYYY, h:mm:ss a');

console.log(formattedDate);

In this example, we import the Moment.js library and create a Moment object using the moment.unix() function. The function takes a Unix timestamp in seconds as an argument.

We then use the format() function to convert the Moment object into a human-readable date and time string.

Code Output:

convert timestamp to date - output 6

Moment.js provides a wide variety of formatting tokens that allow you to customize the output according to your preferences. You can use these tokens to display specific components of the date and time, such as the year, month, day, hour, minute, and second.

Here are a few examples of formatting tokens:

Token Example
YYYY Year with four digits 2023
MMMM Full month name January
D Day of the month 3
h Hour in 12-hour format 1
mm Minutes 23
ss Seconds 54
a AM or PM AM or PM

You can combine these tokens to create the desired format for your date and time string.

JavaScript Convert Timestamp to Date FAQ

Q1: What Is a Unix Timestamp?

A1: A Unix timestamp is a way to represent time as the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC (the Unix epoch). It provides a standardized method for dealing with time across different systems and platforms.

Q2: Why Convert a Unix Timestamp to a Date in JavaScript?

A2: Converting a Unix timestamp to a date in JavaScript is essential for displaying time in a human-readable date format. This conversion allows developers to present timestamps as easily understandable dates and times, improving user experience and readability.

Q3: How Does the JavaScript Date Class Handle Timestamps?

A3: The Date class in JavaScript provides methods to work with dates and times. By creating a new Date object with a Unix timestamp as an argument, you can convert the timestamp into a human-readable date and time representation.

Q4: What Are Some Common Methods for Formatting Dates in JavaScript?

A4: JavaScript offers various methods for formatting dates, including getDate(), getMonth(), getFullYear(), getHours(), getMinutes(), and getSeconds(). These methods allow developers to extract specific components of a date and time for display.

How to Convert Timestamp to Date in JavaScript Conclusion

In conclusion, this tutorial has provided a comprehensive guide on converting Unix timestamps to human-readable dates in JavaScript.

By leveraging the Date class, Intl.DateTimeFormat method, and toLocaleString() method, you can easily transform Unix timestamps into formatted date and time representations. Additionally, the tutorial introduced the usage of the Moment.js library for advanced date formats and time operations, offering a versatile approach to customization.

Whether you prefer the simplicity of built-in JavaScript methods or the flexibility of external libraries, mastering these techniques will empower you to handle timestamps effectively in your JavaScript projects.

To better improve your understanding of how to efficiently utilize date and time in JavaScript, click here to see a tutorial on how to get the current time in JavaScript.