Timestamp Conversion Tips
What Is a Timestamp?
A timestamp is a numeric representation of time, typically referring to the total number of seconds or milliseconds elapsed since January 1, 1970, 00:00:00 Coordinated Universal Time (UTC). Timestamps, due to their system-independent nature, have become the standard way for cross-system time synchronization and data storage. They are widely used in databases, logging systems, and API interfaces.
There are two common timestamp formats: second-level timestamps (10 digits, e.g., 1717200000) and millisecond-level timestamps (13 digits, e.g., 1717200000000). JavaScript's Date.now() returns millisecond-level timestamps, while Unix systems typically use second-level timestamps. This distinction is one of the most common pitfalls for beginners.
Common Pitfalls and Solutions
The first pitfall is timestamp precision confusion. Passing a second-level timestamp directly to JavaScript's Date constructor will cause the time to be incorrectly offset by 1000 times. The solution is to check the number of digits before conversion: 10 digits for seconds, 13 digits for milliseconds.
The second pitfall is timezone issues. Timestamps are in UTC time, but JavaScript's Date object displays them according to the local timezone. When handling cross-timezone applications, pay special attention to timezone conversion between the display layer and storage layer. Using libraries like moment.js or dayjs can simplify timezone handling.
Code Examples
// Get current timestamp
const timestampSeconds = Math.floor(Date.now() / 1000);
const timestampMilliseconds = Date.now();
// Convert timestamp to date
const date = new Date(timestampMilliseconds);
console.log(date.toLocaleString()); // Local time format
// Convert date to timestamp
const specificDate = new Date('2024-06-01T12:00:00Z');
const ts = specificDate.getTime() / 1000; // Second-level timestamp
// Format date output
function formatDate(date, format = 'YYYY-MM-DD HH:mm:ss') {
const pad = n => String(n).padStart(2, '0');
return format
.replace('YYYY', date.getFullYear())
.replace('MM', pad(date.getMonth() + 1))
.replace('DD', pad(date.getDate()))
.replace('HH', pad(date.getHours()))
.replace('mm', pad(date.getMinutes()))
.replace('ss', pad(date.getSeconds()));
}
Recommended Tools
Online timestamp conversion tools can quickly convert between timestamps and date formats. Moment.js and Day.js are the most popular date handling libraries in JavaScript, providing rich APIs and timezone support. For simple scenarios, the native Intl.DateTimeFormat can also meet basic needs.