Tutorials

How to Convert Timestamps in JavaScript: Complete Tutorial with Examples

Introduction

Converting timestamps in JavaScript is a fundamental skill for web developers. Whether you're working with APIs, databases, or user interfaces, you'll frequently need to convert between Unix timestamps and human-readable dates. This tutorial will guide you through everything you need to know.

What You'll Learn

  • ✅ Getting current timestamps
  • ✅ Converting timestamps to Date objects
  • ✅ Converting Date objects to timestamps
  • ✅ Formatting timestamps for display
  • ✅ Handling different timestamp precisions
  • ✅ Working with timezones
  • ✅ Common pitfalls and how to avoid them

Prerequisites

Basic JavaScript knowledge is all you need. No external libraries required for this tutorial (though we'll mention some popular ones at the end).

Step 1: Getting the Current Timestamp

The simplest operation - getting the current time as a timestamp.

Method 1: Date.now() (Recommended)

// Get current timestamp in milliseconds
const timestamp = Date.now();
console.log(timestamp);
// Output: 1704067200000 (13 digits)

Why use this?

  • ✅ Fastest method
  • ✅ No need to create a Date object
  • ✅ Most commonly used

Method 2: new Date().getTime()

// Create Date object and get timestamp
const timestamp = new Date().getTime();
console.log(timestamp);
// Output: 1704067200000 (13 digits)

When to use this?

  • When you already have a Date object
  • When you need to chain methods

Method 3: Unary Plus Operator

// Shorthand using unary plus
const timestamp = +new Date();
console.log(timestamp);
// Output: 1704067200000 (13 digits)

When to use this?

  • Code golf or when brevity matters
  • Not recommended for beginners (less readable)

Getting Timestamp in Seconds

JavaScript uses milliseconds by default, but many APIs use seconds:

// Get timestamp in seconds (10 digits)
const timestampInSeconds = Math.floor(Date.now() / 1000);
console.log(timestampInSeconds);
// Output: 1704067200 (10 digits)

// Alternative: Using parseInt
const timestampSec = parseInt(Date.now() / 1000);
console.log(timestampSec);
// Output: 1704067200

Step 2: Converting Timestamp to Date

Converting a Unix timestamp to a JavaScript Date object.

Basic Conversion

// Millisecond timestamp (13 digits)
const timestamp = 1704067200000;
const date = new Date(timestamp);

console.log(date);
// Output: Mon Jan 01 2024 00:00:00 GMT+0000 (UTC)

console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z

Converting Second Timestamps

Many APIs return timestamps in seconds (10 digits), not milliseconds:

// Second timestamp (10 digits) - MUST multiply by 1000!
const timestampInSeconds = 1704067200;
const date = new Date(timestampInSeconds * 1000);

console.log(date.toISOString());
// Output: 2024-01-01T00:00:00.000Z

⚠️ Common Mistake:

// ❌ WRONG: Using seconds directly
const wrongDate = new Date(1704067200);
console.log(wrongDate.toISOString());
// Output: 1970-01-20T17:27:47.200Z (WRONG!)

// ✅ CORRECT: Multiply by 1000
const correctDate = new Date(1704067200 * 1000);
console.log(correctDate.toISOString());
// Output: 2024-01-01T00:00:00.000Z (CORRECT!)

Detecting Timestamp Precision

Helper function to automatically detect if timestamp is in seconds or milliseconds:

function createDateFromTimestamp(timestamp) {
    // If timestamp has 10 digits, it's in seconds
    // If timestamp has 13 digits, it's in milliseconds
    const digitCount = timestamp.toString().length;

    if (digitCount === 10) {
        // Seconds - multiply by 1000
        return new Date(timestamp * 1000);
    } else if (digitCount === 13) {
        // Milliseconds - use directly
        return new Date(timestamp);
    } else {
        throw new Error(`Invalid timestamp: ${timestamp}`);
    }
}

// Usage
const date1 = createDateFromTimestamp(1704067200);     // 10 digits (seconds)
const date2 = createDateFromTimestamp(1704067200000);  // 13 digits (milliseconds)

console.log(date1.toISOString());  // 2024-01-01T00:00:00.000Z
console.log(date2.toISOString());  // 2024-01-01T00:00:00.000Z

Step 3: Converting Date to Timestamp

Converting a JavaScript Date object back to a Unix timestamp.

From Current Date

const now = new Date();

// Get timestamp in milliseconds
const timestampMs = now.getTime();
console.log(timestampMs);  // 1704067200000

// Get timestamp in seconds
const timestampSec = Math.floor(now.getTime() / 1000);
console.log(timestampSec);  // 1704067200

From Specific Date String

// ISO 8601 format (recommended)
const date1 = new Date('2024-01-01T00:00:00Z');
console.log(date1.getTime());  // 1704067200000

// Different date formats
const date2 = new Date('January 1, 2024');
const date3 = new Date('01/01/2024');
const date4 = new Date('2024-01-01');

console.log(date2.getTime());  // Depends on local timezone
console.log(date3.getTime());  // Depends on local timezone
console.log(date4.getTime());  // Usually 00:00:00 in local timezone

⚠️ Important: Different date string formats behave differently with timezones!

From Date Components

// Create date from year, month, day, etc.
// Note: Month is 0-indexed (0 = January, 11 = December)
const date = new Date(2024, 0, 1, 0, 0, 0);  // Jan 1, 2024, 00:00:00
const timestamp = date.getTime();

console.log(timestamp);  // Local timezone timestamp

// For UTC, use Date.UTC()
const utcTimestamp = Date.UTC(2024, 0, 1, 0, 0, 0);
console.log(utcTimestamp);  // 1704067200000 (UTC)

Step 4: Formatting Timestamps

Converting timestamps to human-readable formats.

Built-in JavaScript Methods

const date = new Date(1704067200000);

// ISO 8601 format (best for APIs)
console.log(date.toISOString());
// Output: "2024-01-01T00:00:00.000Z"

// Locale-specific date string
console.log(date.toLocaleDateString());
// Output: "1/1/2024" (US) or "01/01/2024" (UK)

// Locale-specific date and time
console.log(date.toLocaleString());
// Output: "1/1/2024, 12:00:00 AM"

// Locale-specific time
console.log(date.toLocaleTimeString());
// Output: "12:00:00 AM"

// Full date string
console.log(date.toDateString());
// Output: "Mon Jan 01 2024"

// UTC string
console.log(date.toUTCString());
// Output: "Mon, 01 Jan 2024 00:00:00 GMT"

Custom Formatting

function formatTimestamp(timestamp, format = 'full') {
    const date = new Date(timestamp);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    const formats = {
        'full': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`,
        'date': `${year}-${month}-${day}`,
        'time': `${hours}:${minutes}:${seconds}`,
        'short': `${month}/${day}/${year}`,
        'iso': date.toISOString()
    };

    return formats[format] || formats.full;
}

// Usage
const timestamp = 1704067200000;
console.log(formatTimestamp(timestamp, 'full'));   // "2024-01-01 00:00:00"
console.log(formatTimestamp(timestamp, 'date'));   // "2024-01-01"
console.log(formatTimestamp(timestamp, 'time'));   // "00:00:00"
console.log(formatTimestamp(timestamp, 'short'));  // "01/01/2024"

Using Intl.DateTimeFormat (Modern Approach)

const timestamp = 1704067200000;
const date = new Date(timestamp);

// US English format
const usFormatter = new Intl.DateTimeFormat('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
});
console.log(usFormatter.format(date));
// Output: "January 1, 2024 at 12:00 AM"

// Custom format
const customFormatter = new Intl.DateTimeFormat('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    timeZoneName: 'short'
});
console.log(customFormatter.format(date));
// Output: "Monday, Jan 1, 2024, 12:00:00 AM UTC"

Step 5: Working with Timezones

Handling different timezones is crucial for accurate timestamp conversion.

UTC vs Local Time

const timestamp = 1704067200000;  // Jan 1, 2024, 00:00:00 UTC
const date = new Date(timestamp);

// Get UTC components
console.log('UTC Year:', date.getUTCFullYear());        // 2024
console.log('UTC Month:', date.getUTCMonth() + 1);      // 1
console.log('UTC Date:', date.getUTCDate());            // 1
console.log('UTC Hours:', date.getUTCHours());          // 0

// Get local components (depends on your timezone)
console.log('Local Year:', date.getFullYear());         // 2024
console.log('Local Month:', date.getMonth() + 1);       // 1 (or different)
console.log('Local Date:', date.getDate());             // 1 (or different)
console.log('Local Hours:', date.getHours());           // 0 (or different)

Converting to Specific Timezone

const timestamp = 1704067200000;
const date = new Date(timestamp);

// Display in different timezones using Intl.DateTimeFormat
const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];

timezones.forEach(tz => {
    const formatter = new Intl.DateTimeFormat('en-US', {
        timeZone: tz,
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        timeZoneName: 'short'
    });
    console.log(`${tz}:`, formatter.format(date));
});

// Output:
// America/New_York: 12/31/2023, 07:00:00 PM EST
// Europe/London: 01/01/2024, 12:00:00 AM GMT
// Asia/Tokyo: 01/01/2024, 09:00:00 AM JST

Timezone Offset

const date = new Date();

// Get timezone offset in minutes
const offsetMinutes = date.getTimezoneOffset();
console.log('Offset in minutes:', offsetMinutes);  // e.g., -480 for UTC+8

// Convert to hours
const offsetHours = -offsetMinutes / 60;
console.log('Offset in hours:', offsetHours);  // e.g., 8 for UTC+8

// Format offset as string
const sign = offsetHours >= 0 ? '+' : '-';
const hours = String(Math.abs(Math.floor(offsetHours))).padStart(2, '0');
const minutes = String(Math.abs((offsetHours % 1) * 60)).padStart(2, '0');
console.log(`UTC${sign}${hours}:${minutes}`);  // e.g., "UTC+08:00"

Step 6: Common Pitfalls and Solutions

Pitfall 1: Seconds vs Milliseconds

// ❌ WRONG: Assuming all timestamps are in milliseconds
const wrongDate = new Date(1704067200);  // Treats as milliseconds
console.log(wrongDate.toISOString());     // 1970-01-20T17:27:47.200Z (WRONG!)

// ✅ CORRECT: Check and convert properly
const secondsTimestamp = 1704067200;
const correctDate = new Date(secondsTimestamp * 1000);
console.log(correctDate.toISOString());   // 2024-01-01T00:00:00.000Z (CORRECT!)

Pitfall 2: Month is Zero-Indexed

// ❌ WRONG: Using 1-12 for months
const wrongDate = new Date(2024, 1, 1);  // Creates Feb 1, not Jan 1
console.log(wrongDate.toDateString());   // Thu Feb 01 2024

// ✅ CORRECT: Use 0-11 for months
const correctDate = new Date(2024, 0, 1);  // Creates Jan 1
console.log(correctDate.toDateString());   // Mon Jan 01 2024

Pitfall 3: Timezone Issues with Date Strings

// Different string formats behave differently!

// ISO 8601 with 'Z' - always UTC
const utcDate = new Date('2024-01-01T00:00:00Z');
console.log(utcDate.toISOString());  // 2024-01-01T00:00:00.000Z

// ISO 8601 without 'Z' - treated as local timezone
const localDate = new Date('2024-01-01T00:00:00');
console.log(localDate.toISOString());  // Depends on your timezone

// Date-only format - treated as local timezone at midnight
const dateOnly = new Date('2024-01-01');
console.log(dateOnly.toISOString());  // Usually local midnight

// ✅ BEST PRACTICE: Always use ISO 8601 with 'Z' for UTC
const safeDate = new Date('2024-01-01T00:00:00.000Z');

Pitfall 4: Invalid Dates

// Invalid dates can cause silent errors
const invalidDate = new Date('not a date');
console.log(invalidDate);                 // Invalid Date
console.log(invalidDate.getTime());       // NaN

// ✅ BEST PRACTICE: Always validate
function isValidDate(date) {
    return date instanceof Date && !isNaN(date.getTime());
}

const date1 = new Date('2024-01-01');
const date2 = new Date('invalid');

console.log(isValidDate(date1));  // true
console.log(isValidDate(date2));  // false

Step 7: Practical Examples

Example 1: Display "Time Ago" Format

function timeAgo(timestamp) {
    const now = Date.now();
    const secondsAgo = Math.floor((now - timestamp) / 1000);

    if (secondsAgo < 60) {
        return `${secondsAgo} seconds ago`;
    } else if (secondsAgo < 3600) {
        const minutes = Math.floor(secondsAgo / 60);
        return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
    } else if (secondsAgo < 86400) {
        const hours = Math.floor(secondsAgo / 3600);
        return `${hours} hour${hours > 1 ? 's' : ''} ago`;
    } else {
        const days = Math.floor(secondsAgo / 86400);
        return `${days} day${days > 1 ? 's' : ''} ago`;
    }
}

// Usage
console.log(timeAgo(Date.now() - 30000));      // "30 seconds ago"
console.log(timeAgo(Date.now() - 300000));     // "5 minutes ago"
console.log(timeAgo(Date.now() - 7200000));    // "2 hours ago"
console.log(timeAgo(Date.now() - 172800000));  // "2 days ago"

Example 2: API Response Handler

// Typical API response with timestamps
const apiResponse = {
    created_at: 1704067200,     // Seconds
    updated_at: 1704153600000,  // Milliseconds (mixed precision!)
    expires_at: "2024-01-10T00:00:00Z"  // ISO 8601 string
};

// Convert all to Date objects
function parseApiTimestamps(response) {
    return {
        created: new Date(response.created_at * 1000),  // Convert seconds
        updated: new Date(response.updated_at),          // Already milliseconds
        expires: new Date(response.expires_at)           // Parse ISO string
    };
}

const dates = parseApiTimestamps(apiResponse);
console.log('Created:', dates.created.toLocaleDateString());
console.log('Updated:', dates.updated.toLocaleDateString());
console.log('Expires:', dates.expires.toLocaleDateString());

Example 3: Date Range Validator

function isWithinRange(timestamp, startDate, endDate) {
    const date = new Date(timestamp);
    const start = new Date(startDate);
    const end = new Date(endDate);

    return date >= start && date <= end;
}

// Usage
const eventTimestamp = 1704067200000;  // Jan 1, 2024
const rangeStart = '2024-01-01';
const rangeEnd = '2024-12-31';

console.log(isWithinRange(eventTimestamp, rangeStart, rangeEnd));  // true

Popular Libraries for Advanced Use Cases

For production applications, consider these libraries:

date-fns (Recommended)

import { format, parseISO, formatDistance } from 'date-fns';

// Format timestamp
const timestamp = 1704067200000;
const formatted = format(timestamp, 'PPP');
console.log(formatted);  // "Jan 1st, 2024"

// Time ago
const distance = formatDistance(timestamp, Date.now(), { addSuffix: true });
console.log(distance);  // "2 days ago"

Luxon (Modern, timezone-aware)

import { DateTime } from 'luxon';

// From timestamp
const dt = DateTime.fromMillis(1704067200000);
console.log(dt.toISO());  // "2024-01-01T00:00:00.000Z"

// Timezone conversion
const tokyo = dt.setZone('Asia/Tokyo');
console.log(tokyo.toFormat('yyyy-MM-dd HH:mm:ss'));

Summary

You've learned how to:

  • ✅ Get current timestamps with Date.now()
  • ✅ Convert timestamps to Date objects
  • ✅ Convert Date objects back to timestamps
  • ✅ Format dates for display
  • ✅ Handle different timestamp precisions
  • ✅ Work with timezones
  • ✅ Avoid common pitfalls

Related Tools

Practice what you've learned with our free tools:

Next Steps


Last updated: January 2025

Convert Unix Timestamps Without Mixing Units

JavaScript Date stores milliseconds. Unix timestamps are often expressed in seconds, so multiply seconds by 1000 when creating a Date, then divide by 1000 when converting back.

const seconds = 1_704_067_200;
const date = new Date(seconds * 1000);
const roundTripSeconds = Math.floor(date.getTime() / 1000);

console.log(date.toISOString()); // 2024-01-01T00:00:00.000Z
console.log(roundTripSeconds); // 1704067200

Use the JavaScript Timestamp Helper when you need ready-to-run JavaScript examples. For a broader explanation of parsing, formatting, and browser display, see the complete JavaScript timestamp guide. The Unix Timestamp Converter is useful for checking a value before it reaches code.

Try It Yourself

Test Your Timestamp Conversion

Date result

Need more options? JavaScript Timestamp Helper