JavaScript Timestamp to Date: Convert & Format
Learn to convert a javascript timestamp to date objects in browsers and Node.js. This guide covers milliseconds vs seconds, formatting options, and practical code examples for displaying dates consistently.
JavaScript makes timestamp-to-date conversion straightforward. If you have a timestamp in milliseconds, create a Date object with new Date(timestamp) and then format with toLocaleDateString or toISOString for a standard representation. If your timestamp is in seconds, multiply by 1000 before constructing the Date. This approach works in both Node.js and browsers. javascript timestamp to date
Understanding the javascript timestamp to date semantics
To work effectively with dates in JavaScript, you must understand that the built-in Date object interprets timestamps as milliseconds since the Unix epoch (1970-01-01 UTC). The phrase javascript timestamp to date captures the core problem: converting those numeric values into human-readable dates. In practice, a timestamp is just a number, but how you interpret that number—milliseconds or seconds—determines the exact date you obtain. By mastering this, you gain precise control over formatting, time zones, and locale-specific representations. This section lays the groundwork so you can confidently convert raw numbers into meaningful date strings in both browser and Node.js environments.
Converting timestamps in milliseconds
// milliseconds since Unix epoch
const tsMs = 1625097600000;
const date = new Date(tsMs);
console.log(date.toISOString()); // 2021-07-01T00:00:00.000Z- The Date constructor accepts a millisecond timestamp and returns a Date object.
- toISOString() provides a universal, timezone-free representation (UTC).
- For user-facing displays, consider toLocaleDateString() or Intl.DateTimeFormat for locale control.
Handling timestamps in seconds vs milliseconds
// seconds since Unix epoch
const tsSec = 1625097600;
const dateFromSec = new Date(tsSec * 1000); // convert to milliseconds
console.log(dateFromSec.toUTCString()); // Fri, 01 Jul 2021 00:00:00 GMT- When timestamps are in seconds, multiply by 1000 to align with the millisecond expectation.
- Failing to multiply results in a date close to 1970-01-19, which is almost always incorrect for real data.
- If your API sometimes returns seconds and sometimes milliseconds, you can detect the magnitude and normalize accordingly.
Formatting dates for display
const dt = new Date(1625097600000);
console.log(dt.toLocaleDateString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit' })); // 07/01/2021
console.log(dt.toISOString()); // 2021-07-01T00:00:00.000Z- toLocaleDateString() formats dates in a human-friendly way, respecting locale.
- toISOString() emits a fixed, machine-friendly string in UTC.
- For custom formats, you can assemble parts manually or use Intl.DateTimeFormat.
Time zones and locales
const dt = new Date(1625097600000);
// Local time formatting with explicit locale/timezone
console.log(new Intl.DateTimeFormat('en-US', {
timeZone: 'America/Los_Angeles',
dateStyle: 'medium',
timeStyle: 'short'
}).format(dt)); // Jul 1, 2021, 5:00 AM (PDT) depending on environment- Time zones affect the displayed value; UTC vs local times are common sources of confusion.
- Always document the time zone when storing or transmitting timestamps to avoid misinterpretation.
- Intl.DateTimeFormat provides robust, locale-aware formatting options.
Parsing and validating timestamps from strings
const input = "1625097600000"; // string representing ms
const parsed = Number(input);
if (!Number.isNaN(parsed)) {
const d = new Date(parsed);
console.log(d.toISOString());
} else {
console.error('Invalid timestamp string');
}- Convert strings to numbers before constructing Date.
- Validate with Number.isNaN to avoid runtime errors.
- When parsing, consider potential leading/trailing whitespace or non-numeric characters.
Practical API example: converting API timestamps (seconds) to a standard format
function formatApiTimestamp(ts, unit = 'seconds', locale = 'en-US') {
const ms = unit === 'milliseconds' ? ts : ts * 1000;
const d = new Date(ms);
return {
iso: d.toISOString(),
local: d.toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }),
};
}
console.log(formatApiTimestamp(1625097600, 'seconds'));- This utility handles API timestamps consistently, supporting both seconds and milliseconds.
- Returning both ISO and locale-based strings helps downstream rendering code choose the correct format.
- Defensive checks ensure invalid inputs are handled gracefully.
Common pitfalls and best practices
- Pitfall: Treating timestamps as Date objects without first normalizing units (seconds vs milliseconds).
- Best practice: Normalize to milliseconds early and store a single representation.
- Pitfall: Ignoring time zones when displaying dates to end users.
- Best practice: Prefer explicit locale/timeZone in formatting, or store timestamps in UTC and convert on display.
Using libraries for robust date handling (optional)
// Example with date-fns
import { format } from 'date-fns';
const d = new Date(1625097600000);
console.log(format(d, 'yyyy-MM-dd'));// Example with luxon (if you prefer a dedicated library)
const { DateTime } = require('luxon');
const dt = DateTime.fromMillis(1625097600000, { zone: 'utc' });
console.log(dt.toISO());- Libraries can simplify complex formatting and timezone handling.
- Ensure your build process or runtime supports the chosen library.
- Always test formatting across environments to avoid subtle locale/timezone differences.
Steps
Estimated time: 20-40 minutes
- 1
Identify timestamp units
Inspect API data or input sources to determine if timestamps are in milliseconds or seconds. If you are unsure, check the data range; timestamps in seconds are typically around 10 digits, while milliseconds occupy 13.
Tip: When possible, standardize on milliseconds for clarity. - 2
Normalize to milliseconds
Create a small utility that converts seconds to milliseconds if needed. This ensures consistent Date construction across your codebase.
Tip: Prefer a single normalization point to reduce bugs. - 3
Create a Date object
Use new Date(timestamp) to instantiate a Date. For clarity, store the timestamp in a clearly named variable like tsMs or tsS.
Tip: Verify the resulting date is valid with isNaN(date.getTime()) check. - 4
Format for display
Choose an appropriate formatter: toLocaleDateString for user-facing dates, or toISOString for stable UTC timestamps. Consider Intl.DateTimeFormat for locale-aware output.
Tip: Avoid relying on default string representations for production UIs. - 5
Handle time zones
If your app targets multiple locales, store UTC and format using a specific timeZone when displaying. This avoids drift between client and server.
Tip: Document time zone choices in your data contracts. - 6
Validate and document
Add input validation and tests for edge cases (invalid strings, nulls, or non-numeric inputs). Document assumptions about units and formats in code comments.
Tip: Write tests that cover both milliseconds and seconds inputs.
Prerequisites
Required
- Required
- A modern browser (Chrome, Firefox, Edge) or a JS runtimeRequired
- Basic knowledge of Date objects and timestampsRequired
Optional
- Optional
- Familiarity with Intl.DateTimeFormat for advanced formattingOptional
Keyboard Shortcuts
| Action | Shortcut |
|---|---|
| Format documentVS Code or most editors | ⇧+Alt+F |
| Toggle line commentComment/uncomment a line | Ctrl+/ |
| Open integrated terminalTerminal inside IDE | Ctrl+` |
| Find in filesSearch across project | Ctrl+⇧+F |
Questions & Answers
What is a timestamp in JavaScript?
A timestamp is a numeric value representing a point in time, typically the number of milliseconds since the Unix epoch (January 1, 1970, UTC). JavaScript uses this value to construct Date objects. When you see a timestamp, you are looking at a clock reading that needs interpretation to display a human date.
A timestamp is the milliseconds-since-1970 counter that JavaScript uses to create a date.
How do I convert seconds to milliseconds in JS?
If your timestamp is in seconds, multiply by 1000 to convert to milliseconds before constructing a Date: const d = new Date(seconds * 1000). This is the standard approach to ensure correct dates.
Multiply seconds by 1000 before creating the Date object.
Which format should I use for storing dates?
Store timestamps in UTC milliseconds or store ISO strings. This avoids timezone drift and makes cross-system comparisons straightforward.
Store UTC timestamps or ISO strings to avoid timezone issues.
What if the timestamp is invalid?
Check with isNaN(new Date(ts).getTime()) to detect invalid input. Always validate and handle errors gracefully before formatting dates.
Check for invalid dates and handle gracefully.
Is Date.parse reliable for parsing arbitrary strings?
Date.parse can be unreliable across environments for non-standard formats. Prefer explicit parsing strategies or use a library like date-fns or Luxon for robust parsing.
Date.parse can be flaky; consider a library for parsing.
How can I format dates for multiple locales?
Use Intl.DateTimeFormat with a specified locale and options to control date and time style across locales. This ensures consistent results in all supported regions.
Format with Intl.DateTimeFormat for locale accuracy.
What to Remember
- Convert timestamps with new Date(tsMs) after normalizing units.
- Use toISOString() for UTC and toLocaleDateString() for locale-specific formats.
- Always consider time zones when displaying dates to users.
- Validate inputs and document the unit (ms vs s) at the call site.
