JavaScript: Convert timestamp to date time and vice versa

Updated: February 19, 2023 By: Frienzied Flame Post a comment

This article shows you how to convert Unix timestamp into date time and vice versa in Javascript.

Overview

Unix timestamp is a numeric value that represents the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC. Unix timestamp is easier to store (to databases or files) and process than date time.

On the other hand, date time is the human-readable representation of the Unix timestamp. It is used to represent the date, time, and time zone of a particular moment of life.

The main difference between Unix timestamp and date time is the way in which they are represented. Unix timestamp is represented as a numeric value, whereas date time is represented as a human-readable string.

Turn Unix Timestamp to Human Readable Date Time

In the example below, we create a function named timestampToDate that can take a timestamp and return a human-readable date format:

// define a reusable function
const timestampToDate = (timestamp) => {
  var date = new Date(timestamp * 1000);
  return date.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  });
};

// try it
console.log(timestampToDate(1479693087));
console.log(timestampToDate(1450138800));

Output:

Monday, Nov 21, 2016
Tuesday, Dec 15, 2015

Convert Date Time to Unix Timestamp

To convert a date string to a timestamp, you can follow these steps:

  1. Create a date object with the Date() constructor
  2. Call the getTime() method on the recently created date object, then divide the result by 1000

Words can be confusing and frustrating. Let’s take a look at the code snippet below for more clarity:

const date = new Date('2022-12-30 09:00:00');
const timestamp = date.getTime() / 1000;
console.log(timestamp); 

// use another input with a different date format
const anotherDate = new Date('Dec 31, 2023 18:00:00');
const anotherTimestamp = anotherDate.getTime() / 1000;
console.log(anotherTimestamp);

Output:

1672365600
1704020400

Final Words

With the Date object and its methods, it is convenient to convert between Unix timestamp and date time. This helps you solve a lot of problems with ease, such as the ability to compare two different date times, store date times in a uniform format, and calculate the difference between two date times without any headache.