Try it yourself with our free Epoch Converter tool — runs entirely in your browser, no signup needed.

How to Convert Unix timestamps for API Responses

How to Convert Unix Timestamps for API Responses

When working with APIs, it's common to encounter Unix timestamps, which represent the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC. However, these timestamps are not easily human-readable and often need to be converted to a more readable format for display or further processing. In this guide, we'll explore how to convert Unix timestamps for API responses, covering common scenarios, best practices, and mistakes to avoid.

Quick Example

Here's a minimal JavaScript example that converts a Unix timestamp to a human-readable date string:

// Import the Date constructor
const date = new Date(1643723400 * 1000); // multiply by 1000 to convert seconds to milliseconds

// Format the date as a string
const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false,
});

console.log(formattedDate); // Output: "February 1, 2022, 12:30:00 PM"

This example assumes you have a Unix timestamp in seconds (e.g., 1643723400). Multiply the timestamp by 1000 to convert it to milliseconds, which is what the Date constructor expects.

Real-World Scenarios

Scenario 1: Converting a Single Timestamp

Suppose you receive an API response with a single Unix timestamp:

{
  "created_at": 1643723400
}

You can convert this timestamp using the same approach as the quick example:

const response = { created_at: 1643723400 };
const date = new Date(response.created_at * 1000);
const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false,
});

console.log(formattedDate); // Output: "February 1, 2022, 12:30:00 PM"

Scenario 2: Converting Multiple Timestamps

If your API response contains multiple timestamps, you can use the same approach in a loop:

{
  "data": [
    { "created_at": 1643723400 },
    { "created_at": 1643723401 },
    { "created_at": 1643723402 }
  ]
}
const response = {
  data: [
    { created_at: 1643723400 },
    { created_at: 1643723401 },
    { created_at: 1643723402 },
  ],
};

response.data.forEach((item) => {
  const date = new Date(item.created_at * 1000);
  const formattedDate = date.toLocaleString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric',
    hour12: false,
  });

  console.log(formattedDate);
});

Scenario 3: Handling Timestamps with Milliseconds

Some APIs may return timestamps with milliseconds:

{
  "created_at": 1643723400.123
}

In this case, you can use the same approach, but make sure to multiply the timestamp by 1000 to convert it to milliseconds:

const response = { created_at: 1643723400.123 };
const date = new Date(response.created_at * 1000);
const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  millisecond: 'numeric',
  hour12: false,
});

console.log(formattedDate); // Output: "February 1, 2022, 12:30:00.123 PM"

Scenario 4: Using a Library

If you need to perform more complex date operations, consider using a library like Moment.js:

npm install moment
import moment from 'moment';

const response = { created_at: 1643723400 };
const date = moment.unix(response.created_at).format('YYYY-MM-DD HH:mm:ss');

console.log(date); // Output: "2022-02-01 12:30:00"

Best Practices

  1. Always multiply the timestamp by 1000: When working with Unix timestamps, make sure to multiply the value by 1000 to convert it to milliseconds.
  2. Use the Date constructor: The Date constructor is the most straightforward way to convert Unix timestamps to human-readable dates.
  3. Format dates using toLocaleString: The toLocaleString method provides a flexible way to format dates in various locales.
  4. Consider using a library for complex operations: If you need to perform more complex date operations, consider using a library like Moment.js.
  5. Be mindful of time zones: When working with dates, make sure to consider time zones and adjust the timestamp accordingly.

Common Mistakes

Mistake 1: Forgetting to Multiply by 1000

Incorrect code:

const date = new Date(1643723400);

Corrected code:

const date = new Date(1643723400 * 1000);

Mistake 2: Using the Wrong Locale

Incorrect code:

const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: true,
});

Corrected code:

const formattedDate = date.toLocaleString('en-US', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric',
  hour12: false,
});

Mistake 3: Not Handling Timestamps with Milliseconds

Incorrect code:

const date = new Date(1643723400.123);

Corrected code:

const date = new Date(1643723400.123 * 1000);

FAQ

Q: What is a Unix timestamp?

A Unix timestamp represents the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.

Q: How do I convert a Unix timestamp to a human-readable date?

Use the Date constructor and multiply the timestamp by 1000 to convert it to milliseconds.

Q: What is the difference between Date and moment?

Date is a built-in JavaScript constructor, while moment is a library that provides more advanced date operations.

Q: How do I handle timestamps with milliseconds?

Multiply the timestamp by 1000 to convert it to milliseconds, and use the millisecond option when formatting the date.

Q: What is the best way to format dates in JavaScript?

Use the toLocaleString method to format dates in various locales.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp