In JavaScript, there are often situations where you need to handle date and time values that are in the form of timestamps – a sequence of digits representing the number of seconds that have passed since January 1, 1970 00:00:00 UTC.

For instance, you may receive timestamp data from a database or API response that needs to be displayed to users in a human-readable date/time format. Or you may need to convert a regular date/time value to a timestamp for storage or transmission.

In this comprehensive guide, we will explore the various methods available in JavaScript to convert timestamps to readable date/time strings, as well as go over some common scenarios where you need to do this conversion.

What is a Timestamp?

Before we jump into the conversion methods, let‘s quickly define what a timestamp is exactly:

A timestamp is a sequence of digits representing the number of seconds that have elapsed since midnight UTC on January 1, 1970. This date is known as the Unix Epoch, and is the most widely used base reference point for computer-based timekeeping.

For example, the timestamp value 1667296000 represents the date/time – November 1, 2022 00:00:00 UTC.

Timestamps are useful for recording and transmitting temporal data in an unambiguous way, since they are independent of time zones and calendars. The UNIX epoch format is an industry standard for timestamps.

Why Convert Timestamps to Date/Times?

There are several reasons you may need to convert a numeric timestamp value to a human-readable date/time format in JavaScript:

  • Displaying dates/times in the UI – Timestamps are not user-friendly, so need converting before display
  • Logging events for analysis – Easier to analyze logs with readable timestamps
  • Data processing – Often need to group/filter records by date/time
  • Improving code readability – More clear to see date operations vs timestamp values

Manually parsing the timestamp digits to extract the date and time components is very cumbersome. Luckily, JavaScript provides some simple methods for handling this conversion for you.

Method 1: Using the Date Constructor

The easiest way to convert a timestamp to date/time format is by using the JavaScript Date object constructor.

When passed a timestamp value, the Date constructor will automatically create a new Date instance with its internal UTC time value set to the timestamp.

We can then access this Date instance‘s methods like toLocaleString(), toDateString() etc to format the date/time nicely:

// Timestamp value 
const timestamp = 1667296000;

// Create Date object
const date = new Date(timestamp * 1000);

// Format date/time with toLocaleString()
const formatted = date.toLocaleString(); 

console.log(formatted); // "11/1/2022, 12:00:00 AM"

Notice that we multiplied the timestamp by 1000 before passing it to Date. This is because Javascript expects the value in milliseconds, whereas a typical Unix timestamp is provided in seconds.

Some key points about using the Date constructor for timestamps:

  • Automatically parses timestamp and sets internal UTC time value
  • Requires timestamp in milliseconds (hence multiply by 1000)
  • Allows accessing useful date/time formatting methods like toLocaleString()
  • Very simple, no manual parsing needed

One limitation is that Date objects contain no timezone information. So the date/time will be interpreted as UTC by default. We can overcome this by providing timezone info separately if needed.

Method 2: Manual Parsing with Date/Time Getters

Alternatively, we can manually break down the timestamp and extract the date/time components ourselves using some helpful methods:

// Sample timestamp 
const timestamp = 1667296000;

// Create Date object 
const dateObj = new Date(timestamp * 1000);

// Get date parts
const year = dateObj.getFullYear(); 
const month = dateObj.getMonth() + 1; // 0-indexed
const day = dateObj.getDate();

// Get time parts  
const hours = dateObj.getHours();
const minutes = dateObj.getMinutes();
const seconds = dateObj.getSeconds();

// Construct formatted string
const formatted = `${day}/${month}/${year} ${hours}:${minutes}:${seconds}`; 

console.log(formatted); // "1/11/2022 00:00:00"

The key methods we used above were:

  • getFullYear() – Get 4-digit year
  • getMonth() – Get month number (0-11)
  • getDate() – Get day of month (1-31)
  • getHours() – Get hours (0-23)
  • getMinutes() – Get minutes (0-59)
  • getSeconds() – Get seconds (0-59)

This allows us to break the timestamp down into its individual components programmatically. We simply reconstruct them in a formatted string according to whatever date/time format we want.

The main advantage here is having more control over the final string format compared to Date‘s built-in formatting methods. But it involves more code.

Method 3: Using Moment.js Library

For more advanced date/time formatting and parsing capabilities, consider using the popular Moment.js library.

Moment.js has very flexible capabilities when working with timestamps, dates and times in JavaScript.

To convert a timestamp, we use Moment‘s unix() static method:

import moment from ‘moment‘;

const timestamp = 1667296000;

// Create moment object from timestamp  
const date = moment.unix(timestamp);

// Convert to desired format
const formatted = date.format(‘MMM D, YYYY h:mm:ss A‘);

console.log(formatted); // "Nov 1, 2022 12:00:00 AM"  

The unix() method automatically parses the timestamp value. The format() method allows converting the resulting Moment object to any string date/time format we want.

Some examples of the formatting tokens supported:

  • YYYY – 4 digit year
  • MMM – 3 letter month name
  • DD – Zero-padded day
  • HH – Zero-padded 24 hour
  • And many more

In summary, Moment.js provides:

  • Simple parsing of timestamps via unix()
  • Very flexible date/time formatting capabilities
  • Localization support
  • Timezone support
  • Works nicely with other date libraries like date-fns

The main downside is needing to install the library separately. But for serious date/time handling, Moment.js is likely the best choice.

Scenario 1 – Formatting Timestamps from a Database

A common source of timestamps is from databases that store date/time values in UNIX timestamp format for efficiency.

For example, let‘s say we execute an SQL query and get back rows with a created_at timestamp column:

// Sample DB rows
const rows = [
  { id: 1, created_at: 1667296000 }, 
  { id: 2, created_at: 1667390987 }   
];

We need to format these timestamps nicely before displaying them:

// Loop over rows
for (const row of rows) {

  // Convert timestamp to Date 
  const date = new Date(row.created_at * 1000);

  // Format date/time 
  const formatted = date.toLocaleString();

  // Display formatted date/time  
  console.log(`Record ${row.id} created on: ${formatted}`); 

}

// Logs:  
// Record 1 created on: 11/1/2022, 12:00:00 AM
// Record 2 created on: 11/2/2022, 1:03:07 PM

By handling the conversion directly when processing the raw data, we can display user-friendly dates/times in our application UI.

The same technique works when getting timestamp data from APIs too.

Scenario 2 – Generating Timestamps from Dates

Another scenario is when you need to convert in the other direction – generating a timestamp value from a Date/time string or object.

This is useful when storing or transmitting date values, as the timestamp representation is more compact and standardized.

Here is an example function that converts a Date into a Unix timestamp:

/**
 * Convert Date object to timestamp
 * @param {Date} dateObj 
 * @returns {Number} Timestamp
*/
function dateToTimestamp(dateObj) {
  return dateObj.getTime() / 1000; 
}

// Usage
const date = new Date(); // Current date/time
const timestamp = dateToTimestamp(date); // e.g. 1671090951

By dividing the milliseconds value returned by getTime() by 1000, we get back the seconds-precision Unix timestamp we need.

If starting with a date/time string, first parse into a Date object then extract the timestamp:

// Parse date/time string
const date = new Date(‘December 17, 2022 03:24:00‘);  

// Convert to timestamp
const timestamp = dateToTimestamp(date); // 1671280640

This allows generating timestamps from human-readable dates/times to store or transmit.

Summary

We covered several essential methods for converting Unix timestamps to date/time strings in JavaScript:

  • Date constructor – Simplest way, handles parsing automatically
  • Manual parsing – More control over final format
  • Moment.js library – Advanced formatting and localization

We also looked at some practical examples like handling timestamps from databases or generating timestamps to store dates.

Converting timestamps to readable formats is a common need across most JavaScript projects. Hopefully these techniques give you a solid foundation for tackling timestamp formatting in your own apps!

Similar Posts