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)
1// Get current timestamp in milliseconds 2const timestamp = Date.now(); 3console.log(timestamp); 4// Output: 1704067200000 (13 digits)
Why use this?
- β Fastest method
- β No need to create a Date object
- β Most commonly used
Method 2: new Date().getTime()
1// Create Date object and get timestamp 2const timestamp = new Date().getTime(); 3console.log(timestamp); 4// 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
1// Shorthand using unary plus 2const timestamp = +new Date(); 3console.log(timestamp); 4// 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:
1// Get timestamp in seconds (10 digits) 2const timestampInSeconds = Math.floor(Date.now() / 1000); 3console.log(timestampInSeconds); 4// Output: 1704067200 (10 digits) 5 6// Alternative: Using parseInt 7const timestampSec = parseInt(Date.now() / 1000); 8console.log(timestampSec); 9// Output: 1704067200
Step 2: Converting Timestamp to Date
Converting a Unix timestamp to a JavaScript Date object.
Basic Conversion
1// Millisecond timestamp (13 digits) 2const timestamp = 1704067200000; 3const date = new Date(timestamp); 4 5console.log(date); 6// Output: Mon Jan 01 2024 00:00:00 GMT+0000 (UTC) 7 8console.log(date.toISOString()); 9// Output: 2024-01-01T00:00:00.000Z
Converting Second Timestamps
Many APIs return timestamps in seconds (10 digits), not milliseconds:
1// Second timestamp (10 digits) - MUST multiply by 1000! 2const timestampInSeconds = 1704067200; 3const date = new Date(timestampInSeconds * 1000); 4 5console.log(date.toISOString()); 6// Output: 2024-01-01T00:00:00.000Z
β οΈ Common Mistake:
1// β WRONG: Using seconds directly 2const wrongDate = new Date(1704067200); 3console.log(wrongDate.toISOString()); 4// Output: 1970-01-20T17:27:47.200Z (WRONG!) 5 6// β CORRECT: Multiply by 1000 7const correctDate = new Date(1704067200 * 1000); 8console.log(correctDate.toISOString()); 9// Output: 2024-01-01T00:00:00.000Z (CORRECT!)
Detecting Timestamp Precision
Helper function to automatically detect if timestamp is in seconds or milliseconds:
1function createDateFromTimestamp(timestamp) { 2 // If timestamp has 10 digits, it's in seconds 3 // If timestamp has 13 digits, it's in milliseconds 4 const digitCount = timestamp.toString().length; 5 6 if (digitCount === 10) { 7 // Seconds - multiply by 1000 8 return new Date(timestamp * 1000); 9 } else if (digitCount === 13) { 10 // Milliseconds - use directly 11 return new Date(timestamp); 12 } else { 13 throw new Error(`Invalid timestamp: ${timestamp}`); 14 } 15} 16 17// Usage 18const date1 = createDateFromTimestamp(1704067200); // 10 digits (seconds) 19const date2 = createDateFromTimestamp(1704067200000); // 13 digits (milliseconds) 20 21console.log(date1.toISOString()); // 2024-01-01T00:00:00.000Z 22console.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
1const now = new Date(); 2 3// Get timestamp in milliseconds 4const timestampMs = now.getTime(); 5console.log(timestampMs); // 1704067200000 6 7// Get timestamp in seconds 8const timestampSec = Math.floor(now.getTime() / 1000); 9console.log(timestampSec); // 1704067200
From Specific Date String
1// ISO 8601 format (recommended) 2const date1 = new Date('2024-01-01T00:00:00Z'); 3console.log(date1.getTime()); // 1704067200000 4 5// Different date formats 6const date2 = new Date('January 1, 2024'); 7const date3 = new Date('01/01/2024'); 8const date4 = new Date('2024-01-01'); 9 10console.log(date2.getTime()); // Depends on local timezone 11console.log(date3.getTime()); // Depends on local timezone 12console.log(date4.getTime()); // Usually 00:00:00 in local timezone
β οΈ Important: Different date string formats behave differently with timezones!
From Date Components
1// Create date from year, month, day, etc. 2// Note: Month is 0-indexed (0 = January, 11 = December) 3const date = new Date(2024, 0, 1, 0, 0, 0); // Jan 1, 2024, 00:00:00 4const timestamp = date.getTime(); 5 6console.log(timestamp); // Local timezone timestamp 7 8// For UTC, use Date.UTC() 9const utcTimestamp = Date.UTC(2024, 0, 1, 0, 0, 0); 10console.log(utcTimestamp); // 1704067200000 (UTC)
Step 4: Formatting Timestamps
Converting timestamps to human-readable formats.
Built-in JavaScript Methods
1const date = new Date(1704067200000); 2 3// ISO 8601 format (best for APIs) 4console.log(date.toISOString()); 5// Output: "2024-01-01T00:00:00.000Z" 6 7// Locale-specific date string 8console.log(date.toLocaleDateString()); 9// Output: "1/1/2024" (US) or "01/01/2024" (UK) 10 11// Locale-specific date and time 12console.log(date.toLocaleString()); 13// Output: "1/1/2024, 12:00:00 AM" 14 15// Locale-specific time 16console.log(date.toLocaleTimeString()); 17// Output: "12:00:00 AM" 18 19// Full date string 20console.log(date.toDateString()); 21// Output: "Mon Jan 01 2024" 22 23// UTC string 24console.log(date.toUTCString()); 25// Output: "Mon, 01 Jan 2024 00:00:00 GMT"
Custom Formatting
1function formatTimestamp(timestamp, format = 'full') { 2 const date = new Date(timestamp); 3 4 const year = date.getFullYear(); 5 const month = String(date.getMonth() + 1).padStart(2, '0'); 6 const day = String(date.getDate()).padStart(2, '0'); 7 const hours = String(date.getHours()).padStart(2, '0'); 8 const minutes = String(date.getMinutes()).padStart(2, '0'); 9 const seconds = String(date.getSeconds()).padStart(2, '0'); 10 11 const formats = { 12 'full': `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`, 13 'date': `${year}-${month}-${day}`, 14 'time': `${hours}:${minutes}:${seconds}`, 15 'short': `${month}/${day}/${year}`, 16 'iso': date.toISOString() 17 }; 18 19 return formats[format] || formats.full; 20} 21 22// Usage 23const timestamp = 1704067200000; 24console.log(formatTimestamp(timestamp, 'full')); // "2024-01-01 00:00:00" 25console.log(formatTimestamp(timestamp, 'date')); // "2024-01-01" 26console.log(formatTimestamp(timestamp, 'time')); // "00:00:00" 27console.log(formatTimestamp(timestamp, 'short')); // "01/01/2024"
Using Intl.DateTimeFormat (Modern Approach)
1const timestamp = 1704067200000; 2const date = new Date(timestamp); 3 4// US English format 5const usFormatter = new Intl.DateTimeFormat('en-US', { 6 year: 'numeric', 7 month: 'long', 8 day: 'numeric', 9 hour: '2-digit', 10 minute: '2-digit' 11}); 12console.log(usFormatter.format(date)); 13// Output: "January 1, 2024 at 12:00 AM" 14 15// Custom format 16const customFormatter = new Intl.DateTimeFormat('en-US', { 17 weekday: 'long', 18 year: 'numeric', 19 month: 'short', 20 day: 'numeric', 21 hour: '2-digit', 22 minute: '2-digit', 23 second: '2-digit', 24 timeZoneName: 'short' 25}); 26console.log(customFormatter.format(date)); 27// 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
1const timestamp = 1704067200000; // Jan 1, 2024, 00:00:00 UTC 2const date = new Date(timestamp); 3 4// Get UTC components 5console.log('UTC Year:', date.getUTCFullYear()); // 2024 6console.log('UTC Month:', date.getUTCMonth() + 1); // 1 7console.log('UTC Date:', date.getUTCDate()); // 1 8console.log('UTC Hours:', date.getUTCHours()); // 0 9 10// Get local components (depends on your timezone) 11console.log('Local Year:', date.getFullYear()); // 2024 12console.log('Local Month:', date.getMonth() + 1); // 1 (or different) 13console.log('Local Date:', date.getDate()); // 1 (or different) 14console.log('Local Hours:', date.getHours()); // 0 (or different)
Converting to Specific Timezone
1const timestamp = 1704067200000; 2const date = new Date(timestamp); 3 4// Display in different timezones using Intl.DateTimeFormat 5const timezones = ['America/New_York', 'Europe/London', 'Asia/Tokyo']; 6 7timezones.forEach(tz => { 8 const formatter = new Intl.DateTimeFormat('en-US', { 9 timeZone: tz, 10 year: 'numeric', 11 month: '2-digit', 12 day: '2-digit', 13 hour: '2-digit', 14 minute: '2-digit', 15 second: '2-digit', 16 timeZoneName: 'short' 17 }); 18 console.log(`${tz}:`, formatter.format(date)); 19}); 20 21// Output: 22// America/New_York: 12/31/2023, 07:00:00 PM EST 23// Europe/London: 01/01/2024, 12:00:00 AM GMT 24// Asia/Tokyo: 01/01/2024, 09:00:00 AM JST
Timezone Offset
1const date = new Date(); 2 3// Get timezone offset in minutes 4const offsetMinutes = date.getTimezoneOffset(); 5console.log('Offset in minutes:', offsetMinutes); // e.g., -480 for UTC+8 6 7// Convert to hours 8const offsetHours = -offsetMinutes / 60; 9console.log('Offset in hours:', offsetHours); // e.g., 8 for UTC+8 10 11// Format offset as string 12const sign = offsetHours >= 0 ? '+' : '-'; 13const hours = String(Math.abs(Math.floor(offsetHours))).padStart(2, '0'); 14const minutes = String(Math.abs((offsetHours % 1) * 60)).padStart(2, '0'); 15console.log(`UTC${sign}${hours}:${minutes}`); // e.g., "UTC+08:00"
Step 6: Common Pitfalls and Solutions
Pitfall 1: Seconds vs Milliseconds
1// β WRONG: Assuming all timestamps are in milliseconds 2const wrongDate = new Date(1704067200); // Treats as milliseconds 3console.log(wrongDate.toISOString()); // 1970-01-20T17:27:47.200Z (WRONG!) 4 5// β CORRECT: Check and convert properly 6const secondsTimestamp = 1704067200; 7const correctDate = new Date(secondsTimestamp * 1000); 8console.log(correctDate.toISOString()); // 2024-01-01T00:00:00.000Z (CORRECT!)
Pitfall 2: Month is Zero-Indexed
1// β WRONG: Using 1-12 for months 2const wrongDate = new Date(2024, 1, 1); // Creates Feb 1, not Jan 1 3console.log(wrongDate.toDateString()); // Thu Feb 01 2024 4 5// β CORRECT: Use 0-11 for months 6const correctDate = new Date(2024, 0, 1); // Creates Jan 1 7console.log(correctDate.toDateString()); // Mon Jan 01 2024
Pitfall 3: Timezone Issues with Date Strings
1// Different string formats behave differently! 2 3// ISO 8601 with 'Z' - always UTC 4const utcDate = new Date('2024-01-01T00:00:00Z'); 5console.log(utcDate.toISOString()); // 2024-01-01T00:00:00.000Z 6 7// ISO 8601 without 'Z' - treated as local timezone 8const localDate = new Date('2024-01-01T00:00:00'); 9console.log(localDate.toISOString()); // Depends on your timezone 10 11// Date-only format - treated as local timezone at midnight 12const dateOnly = new Date('2024-01-01'); 13console.log(dateOnly.toISOString()); // Usually local midnight 14 15// β BEST PRACTICE: Always use ISO 8601 with 'Z' for UTC 16const safeDate = new Date('2024-01-01T00:00:00.000Z');
Pitfall 4: Invalid Dates
1// Invalid dates can cause silent errors 2const invalidDate = new Date('not a date'); 3console.log(invalidDate); // Invalid Date 4console.log(invalidDate.getTime()); // NaN 5 6// β BEST PRACTICE: Always validate 7function isValidDate(date) { 8 return date instanceof Date && !isNaN(date.getTime()); 9} 10 11const date1 = new Date('2024-01-01'); 12const date2 = new Date('invalid'); 13 14console.log(isValidDate(date1)); // true 15console.log(isValidDate(date2)); // false
Step 7: Practical Examples
Example 1: Display "Time Ago" Format
1function timeAgo(timestamp) { 2 const now = Date.now(); 3 const secondsAgo = Math.floor((now - timestamp) / 1000); 4 5 if (secondsAgo < 60) { 6 return `${secondsAgo} seconds ago`; 7 } else if (secondsAgo < 3600) { 8 const minutes = Math.floor(secondsAgo / 60); 9 return `${minutes} minute${minutes > 1 ? 's' : ''} ago`; 10 } else if (secondsAgo < 86400) { 11 const hours = Math.floor(secondsAgo / 3600); 12 return `${hours} hour${hours > 1 ? 's' : ''} ago`; 13 } else { 14 const days = Math.floor(secondsAgo / 86400); 15 return `${days} day${days > 1 ? 's' : ''} ago`; 16 } 17} 18 19// Usage 20console.log(timeAgo(Date.now() - 30000)); // "30 seconds ago" 21console.log(timeAgo(Date.now() - 300000)); // "5 minutes ago" 22console.log(timeAgo(Date.now() - 7200000)); // "2 hours ago" 23console.log(timeAgo(Date.now() - 172800000)); // "2 days ago"
Example 2: API Response Handler
1// Typical API response with timestamps 2const apiResponse = { 3 created_at: 1704067200, // Seconds 4 updated_at: 1704153600000, // Milliseconds (mixed precision!) 5 expires_at: "2024-01-10T00:00:00Z" // ISO 8601 string 6}; 7 8// Convert all to Date objects 9function parseApiTimestamps(response) { 10 return { 11 created: new Date(response.created_at * 1000), // Convert seconds 12 updated: new Date(response.updated_at), // Already milliseconds 13 expires: new Date(response.expires_at) // Parse ISO string 14 }; 15} 16 17const dates = parseApiTimestamps(apiResponse); 18console.log('Created:', dates.created.toLocaleDateString()); 19console.log('Updated:', dates.updated.toLocaleDateString()); 20console.log('Expires:', dates.expires.toLocaleDateString());
Example 3: Date Range Validator
1function isWithinRange(timestamp, startDate, endDate) { 2 const date = new Date(timestamp); 3 const start = new Date(startDate); 4 const end = new Date(endDate); 5 6 return date >= start && date <= end; 7} 8 9// Usage 10const eventTimestamp = 1704067200000; // Jan 1, 2024 11const rangeStart = '2024-01-01'; 12const rangeEnd = '2024-12-31'; 13 14console.log(isWithinRange(eventTimestamp, rangeStart, rangeEnd)); // true
Popular Libraries for Advanced Use Cases
For production applications, consider these libraries:
date-fns (Recommended)
1import { format, parseISO, formatDistance } from 'date-fns'; 2 3// Format timestamp 4const timestamp = 1704067200000; 5const formatted = format(timestamp, 'PPP'); 6console.log(formatted); // "Jan 1st, 2024" 7 8// Time ago 9const distance = formatDistance(timestamp, Date.now(), { addSuffix: true }); 10console.log(distance); // "2 days ago"
Luxon (Modern, timezone-aware)
1import { DateTime } from 'luxon'; 2 3// From timestamp 4const dt = DateTime.fromMillis(1704067200000); 5console.log(dt.toISO()); // "2024-01-01T00:00:00.000Z" 6 7// Timezone conversion 8const tokyo = dt.setZone('Asia/Tokyo'); 9console.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:
- Unix Timestamp Converter - Interactive timestamp conversion
- Current Timestamp - Get current time in various formats
- JavaScript Timestamp Helper - JavaScript-specific tools
- Batch Timestamp Converter - Convert multiple timestamps
Next Steps
- Learn about Timestamp Precision Levels
- Explore Understanding Timezones
- Read about The Year 2038 Problem
Last updated: January 2025