JavaScript Unix Timestamp Guide
A comprehensive guide to working with Unix timestamps in JavaScript and Node.js. Learn how to get the current timestamp, convert between timestamps and Date objects, format dates, and handle timezones.
Quick Reference
Get Current Timestamp
Date.now()Timestamp to Date
new Date(timestamp * 1000)Date to Timestamp
Math.floor(date.getTime() / 1000)Current Time (seconds)
Math.floor(Date.now() / 1000)Getting the Current Unix Timestamp
JavaScript provides several ways to get the current Unix timestamp:
// Get current timestamp in milliseconds const timestampMs = Date.now() console.log(timestampMs) // Output: 1733616000123 // Get current timestamp in seconds (Unix timestamp) const timestamp = Math.floor(Date.now() / 1000) console.log(timestamp) // Output: 1733616000 // Alternative methods const timestamp2 = Math.floor(new Date().getTime() / 1000) const timestamp3 = Math.floor(+new Date() / 1000) // All produce the same result console.log(timestamp === timestamp2 === timestamp3) // true
Note: JavaScript's Date.now() returns milliseconds. Divide by 1000 and use Math.floor() to get Unix timestamp in seconds.
Converting Timestamp to Date
Convert a Unix timestamp to a JavaScript Date object:
// Convert timestamp (seconds) to Date const timestamp = 1733616000 const date = new Date(timestamp * 1000) // Multiply by 1000! console.log(date) // Date object console.log(date.toString()) // Output: Fri Dec 07 2024 18:00:00 GMT+0000 // Format the date console.log(date.toISOString()) // Output: 2024-12-07T18:00:00.000Z console.log(date.toLocaleDateString()) // Output: 12/7/2024 (depends on locale) console.log(date.toLocaleString()) // Output: 12/7/2024, 6:00:00 PM console.log(date.toUTCString()) // Output: Fri, 07 Dec 2024 18:00:00 GMT // Convert millisecond timestamp const timestampMs = 1733616000123 const date2 = new Date(timestampMs) // No need to multiply
Important: Always multiply Unix timestamps (in seconds) by 1000 before passing to new Date() since it expects milliseconds!
Converting Date to Timestamp
Convert a Date object or date string to a Unix timestamp:
// Current date to timestamp
const now = new Date()
const timestamp = Math.floor(now.getTime() / 1000)
console.log(timestamp) // Output: 1733616000
// Specific date to timestamp
const date = new Date('2024-12-07T18:00:00Z')
const timestamp2 = Math.floor(date.getTime() / 1000)
console.log(timestamp2) // Output: 1733616000
// Using valueOf() (same as getTime())
const timestamp3 = Math.floor(date.valueOf() / 1000)
// Date string to timestamp
const dateString = '2024-12-07'
const timestamp4 = Math.floor(new Date(dateString).getTime() / 1000)
// Create specific date
const specificDate = new Date(2024, 11, 7, 18, 0, 0) // Note: Month is 0-indexed!
const timestamp5 = Math.floor(specificDate.getTime() / 1000)
// Get millisecond timestamp (no division needed)
const timestampMs = now.getTime()
console.log(timestampMs) // Output: 1733616000123Formatting Dates
Format timestamps into readable date strings:
const timestamp = 1733616000
const date = new Date(timestamp * 1000)
// Built-in methods
console.log(date.toISOString())
// 2024-12-07T18:00:00.000Z
console.log(date.toLocaleDateString('en-US'))
// 12/7/2024
console.log(date.toLocaleTimeString('en-US'))
// 6:00:00 PM
console.log(date.toLocaleString('en-US'))
// 12/7/2024, 6:00:00 PM
// Using Intl.DateTimeFormat for more control
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
})
console.log(formatter.format(date))
// December 7, 2024 at 6:00:00 PM GMT
// Custom format function
function formatDate(date) {
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')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
console.log(formatDate(date))
// 2024-12-07 18:00:00Working with Timezones
Handle different timezones using the Intl API:
const timestamp = 1733616000
const date = new Date(timestamp * 1000)
// Display in different timezones
const nyTime = new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
dateStyle: 'full',
timeStyle: 'long'
}).format(date)
console.log(nyTime)
// Friday, December 7, 2024 at 1:00:00 PM EST
const tokyoTime = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Tokyo',
dateStyle: 'full',
timeStyle: 'long'
}).format(date)
console.log(tokyoTime)
// Saturday, December 8, 2024 at 3:00:00 AM JST
const londonTime = new Intl.DateTimeFormat('en-GB', {
timeZone: 'Europe/London',
dateStyle: 'full',
timeStyle: 'long'
}).format(date)
console.log(londonTime)
// Friday, 7 December 2024 at 18:00:00 GMT
// Get timezone offset
const offset = date.getTimezoneOffset()
console.log(`Offset: ${offset} minutes`)
// Convert to UTC explicitly
const utcDate = new Date(date.toUTCString())
console.log(utcDate.toISOString())Common Use Cases
Calculate Time Difference
// Calculate difference between two timestamps
const timestamp1 = 1733616000
const timestamp2 = 1733619600
const diffSeconds = timestamp2 - timestamp1
const diffMinutes = diffSeconds / 60
const diffHours = diffSeconds / 3600
const diffDays = diffSeconds / 86400
console.log(`Difference: ${diffSeconds} seconds`)
console.log(`Difference: ${diffHours} hours`)
console.log(`Difference: ${diffDays} days`)
// Human-readable difference
function getTimeDifference(timestamp1, timestamp2) {
const diff = Math.abs(timestamp2 - timestamp1)
const days = Math.floor(diff / 86400)
const hours = Math.floor((diff % 86400) / 3600)
const minutes = Math.floor((diff % 3600) / 60)
const seconds = diff % 60
return `${days}d ${hours}h ${minutes}m ${seconds}s`
}
console.log(getTimeDifference(timestamp1, timestamp2))
// Output: 0d 1h 0m 0sGet Start of Day Timestamp
// Get timestamp for start of today (00:00:00) const now = new Date() const startOfDay = new Date(now.setHours(0, 0, 0, 0)) const timestamp = Math.floor(startOfDay.getTime() / 1000) console.log(timestamp) // Start of day in UTC const startOfDayUTC = new Date(Date.UTC( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() )) const timestampUTC = Math.floor(startOfDayUTC.getTime() / 1000) console.log(timestampUTC)
Validate Timestamp
function isValidTimestamp(timestamp) {
// Check if it's a number
if (typeof timestamp !== 'number' || isNaN(timestamp)) {
return false
}
// Check if timestamp is in reasonable range
// Between Jan 1, 1970 and Jan 1, 2100
const minTimestamp = 0
const maxTimestamp = 4102444800 // Jan 1, 2100
if (timestamp < minTimestamp || timestamp > maxTimestamp) {
return false
}
// Try to create a valid date
const date = new Date(timestamp * 1000)
return !isNaN(date.getTime())
}
console.log(isValidTimestamp(1733616000)) // true
console.log(isValidTimestamp(-1000)) // false
console.log(isValidTimestamp(9999999999)) // false
console.log(isValidTimestamp('abc')) // falseBest Practices
Use Date.now() for current timestamp
It's faster than new Date().getTime()
Always multiply Unix timestamps by 1000
JavaScript Date expects milliseconds, Unix timestamps are in seconds
Store timestamps in UTC
Convert to local timezone only for display
Use ISO 8601 format for APIs
Use toISOString() for consistent date exchange
Consider using libraries for complex operations
date-fns, dayjs, or Luxon provide better timezone and formatting support
Remember months are 0-indexed
January is 0, December is 11 in Date constructor