Timestamp is a common way to represent date and time in computers. It is simple, precise, and easy to process. This article explores the principles of timestamps, various conversion methods, and practical application scenarios in depth.
I. Timestamp Principles
A timestamp is the number of seconds or milliseconds counted from January 1, 1970, 00:00:00 UTC (the Unix epoch). The choice of the Unix epoch is not accidental; it is the birth time of the Unix operating system. This choice has made timestamps a universal time representation across platforms and languages.
Historical Background
The Unix epoch was chosen 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' — on January 19, 2038, 32-bit timestamps will overflow. Modern systems generally use 64-bit integers, which can represent time up to about 58 billion years from now.
Precision Description
Timestamp precision is divided into second-level and millisecond-level. Second-level timestamps (10 digits) have second precision, suitable for scenarios that don't require millisecond precision; millisecond-level timestamps (13 digits) have millisecond precision, suitable for scenarios requiring millisecond accuracy, such as real-time data processing, logging, etc.
| Type | Unit | Example |
|---|---|---|
| Unix 时间戳(秒) | 秒 | 1715068800 |
| JavaScript 时间戳(毫秒) | 毫秒 | 1715068800000 |
| 微秒时间戳 | 微秒 | 1715068800000000 |
II. Timestamp Operations in JavaScript
2.1 Getting 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
III. 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;
IV. 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 if cache has expired:
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);
V. Advanced Techniques
5.1 Timezone Handling Explained
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 Handling
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
| Problem | Cause | Solution |
|---|---|---|
| Unit error | Mixing seconds and milliseconds | Unify using milliseconds or clearly indicate units |
| Timezone offset | Local timezone inconsistent with server timezone | Unify using UTC time |
| Date string parsing | Inconsistent parsing across browsers | Manual parsing or use standard formats |
| Overflow issue | Maximum timestamp limit on 32-bit systems | Use millisecond timestamps or BigInt |
VI. Comparison of Date/Time Libraries
Choosing the right date processing library:
| Library | Size | Features |
|---|---|---|
| 原生 Date | 0 KB | No dependencies, limited functionality |
| Day.js | 2 KB | Lightweight, Moment.js-like API |
| Moment.js | 32 KB | Powerful features, no longer maintained |
| date-fns | On-demand loading | Functional, supports Tree Shaking |
VII. Using TudoSi Tools for Timestamp Processing
TudoSi Tools provides convenient timestamp conversion features:
- Support second, millisecond, and microsecond timestamp conversion
- Support multiple date format outputs
- Support timezone conversion
- Real-time preview of conversion results
VIII. Summary
Timestamp is a fundamental concept for handling date and time. Mastering its principles and conversion methods is crucial for development work. TudoSi Tools' timestamp conversion feature can help you quickly complete various time-related tasks.