Timestamps are a common way to represent dates and times in computing. They are simple, precise and easy to handle. This article explores timestamp principles, conversion methods and practical applications.
1. Timestamp Principles
A timestamp is the number of seconds or milliseconds since January 1, 1970, 00:00:00 UTC (Unix epoch). The choice of the Unix epoch was not accidental; it is the birth time of the Unix operating system, and this choice makes timestamps a universal time representation across platforms and languages.
Historical Background
The choice of the Unix epoch was made by Unix developers Dennis Ritchie and Ken Thompson in 1971. Initially, timestamps were represented using 32-bit integers, which led to the famous 'Year 2038 problem' — by January 19, 2038, 32-bit timestamps would overflow. Modern systems generally use 64-bit integers, which can represent times up to approximately 58 billion years from now.
Precision Explanation
Timestamp precision is divided into second-level and millisecond-level. Second-level timestamps (10-digit numbers) have second precision, suitable for scenarios that do not require millisecond-level precision; millisecond-level timestamps (13-digit numbers) have millisecond precision, suitable for scenarios that require precision to the millisecond, such as real-time data processing, logging, etc.
| Type | Unit | Example |
|---|---|---|
| Unix 时间戳(秒) | 秒 | 1715068800 |
| JavaScript 时间戳(毫秒) | 毫秒 | 1715068800000 |
| 微秒时间戳 | 微秒 | 1715068800000000 |
2. Timestamp Operations in JavaScript
2.1 Get Current Timestamp
// 获取毫秒时间戳
const timestampMs = Date.now();
// 1715068800000
// 使用 Date 对象
const timestampMs2 = new Date().getTime();
// 1715068800000
// 获取秒时间戳
const timestampSec = Math.floor(Date.now() / 1000);
// 1715068800
2.2 Timestamp to Date Object
const timestamp = 1715068800000;
const date = new Date(timestamp);
console.log(date.getFullYear()); // 2026
console.log(date.getMonth() + 1); // 5 (月份从0开始)
console.log(date.getDate()); // 6
console.log(date.getHours()); // 0
console.log(date.getMinutes()); // 0
2.3 Timestamp Formatting
function formatTimestamp(timestamp, format = 'YYYY-MM-DD HH:mm:ss') {
const date = new Date(timestamp);
const pad = (n) => n.toString().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()));
}
console.log(formatTimestamp(1715068800000));
// 2026-05-06 00:00:00
3. Timestamp Conversion
3.1 Date String to Timestamp
const dateStr = '2026-05-06';
const timestamp = new Date(dateStr).getTime();
// 1715068800000
// 指定时区
const timestampUTC = new Date('2026-05-06T00:00:00Z').getTime();
3.2 Timezone Conversion
// 获取 UTC 时间戳
const utcDate = new Date(Date.UTC(2026, 4, 6));
const utcTimestamp = utcDate.getTime();
// 本地时间转 UTC
const localDate = new Date();
const utcTimestamp2 = localDate.getTime() - localDate.getTimezoneOffset() * 60000;
4. Common Application Scenarios
4.1 Database Storage
Most databases support timestamp types:
// MySQL
CREATE TABLE events (
id INT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
// MongoDB
{
"_id": ObjectId(),
"createdAt": ISODate("2026-05-06T00:00:00Z")
}
4.2 Cache Control
Using timestamps to determine cache expiration:
const cache = {
data: null,
timestamp: 0,
ttl: 3600000 // 1小时
};
function getData() {
const now = Date.now();
if (cache.data && now - cache.timestamp < cache.ttl) {
return cache.data;
}
// 重新获取数据
cache.data = fetchData();
cache.timestamp = now;
return cache.data;
}
4.3 Data Sorting
Sorting data by time:
const posts = [
{ id: 1, createdAt: 1715068800000 },
{ id: 2, createdAt: 1714982400000 },
{ id: 3, createdAt: 1715155200000 }
];
// 按时间降序排序
posts.sort((a, b) => b.createdAt - a.createdAt);
5. Advanced Techniques
5.1 Timezone Handling Deep Dive
Timezone handling in JavaScript:
// 获取当前时区偏移(分钟)
const offset = new Date().getTimezoneOffset();
// 中国时区:-480(UTC+8)
// 格式化不同时区的时间
function formatTimezone(date, timezone) {
return date.toLocaleString('zh-CN', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
}
console.log(formatTimezone(new Date(), 'UTC'));
console.log(formatTimezone(new Date(), 'Asia/Shanghai'));
console.log(formatTimezone(new Date(), 'America/New_York'));
5.2 Daylight Saving Time
Detecting and handling daylight saving time:
function isDaylightSavingTime(date, timezone = 'America/New_York') {
const jan = new Date(date.getFullYear(), 0, 1);
const jul = new Date(date.getFullYear(), 6, 1);
const stdTimezoneOffset = Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
return date.getTimezoneOffset() < stdTimezoneOffset;
}
console.log(isDaylightSavingTime(new Date()));
// 输出当前是否处于夏令时
5.3 Relative Time Formatting
Converting timestamps to relative time descriptions:
function formatRelativeTime(timestamp) {
const now = Date.now();
const diff = now - timestamp;
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
const week = 7 * day;
const month = 30 * day;
const year = 365 * day;
if (diff < minute) return '刚刚';
if (diff < hour) return `${Math.floor(diff / minute)}分钟前`;
if (diff < day) return `${Math.floor(diff / hour)}小时前`;
if (diff < week) return `${Math.floor(diff / day)}天前`;
if (diff < month) return `${Math.floor(diff / week)}周前`;
if (diff < year) return `${Math.floor(diff / month)}月前`;
return `${Math.floor(diff / year)}年前`;
}
console.log(formatRelativeTime(Date.now() - 3600000)); // 1小时前
5.4 Common Issues and Debugging
| Issue | Cause | Solution |
|---|---|---|
| Unit Error | Mixing seconds and milliseconds | Use milliseconds consistently or clearly indicate units |
| Timezone Offset | Local timezone differs from server timezone | Use UTC time consistently |
| Date String Parsing | Inconsistent parsing across browsers | Parse manually or use standard format |
| Overflow Issue | 32-bit system maximum timestamp limit | Use millisecond timestamps or BigInt |
6. Date/time Library Comparison
Choose the right date handling library:
| Library | Size | Features |
|---|---|---|
| 原生 Date | 0 KB | No dependencies, limited features |
| Day.js | 2 KB | Lightweight, Moment.js-like API |
| Moment.js | 32 KB | Powerful, no longer maintained |
| date-fns | Tree-shakable | Functional, supports Tree Shaking |
7. Using Tudousi Tools for Timestamps
Tudousi Tools provides convenient timestamp conversion features:
- Supports second, millisecond, microsecond timestamp conversion
- Supports multiple date format outputs
- Supports timezone conversion
- Real-time preview of conversion results
8. Summary
Timestamps are fundamental concepts for handling dates and times. Mastering their principles and conversion methods is crucial for development work. Tudousi Tools' timestamp conversion feature helps you quickly complete various time-related tasks.