JavaScript获取当前时间的方法汇总(含格式化输出)
原创
2025-07-10 09:52:07编程技术
589
在Web开发中,时间处理是核心功能之一,从页面实时时钟到数据记录的时间戳,再到复杂的日历应用,都需要精确获取和格式化当前时间。本文ZHANID工具网将系统梳理JavaScript中获取当前时间的15种核心方法,涵盖原生API、现代浏览器扩展、第三方库及特殊场景解决方案,并提供格式化输出技巧,帮助开发者构建高效可靠的时间处理逻辑。
一、原生JavaScript时间获取方法
1. 基础Date对象const now = new Date();
console.log(now); // 输出: Wed May 15 2024 14:30:45 GMT+0800 (中国标准时间)特性:
返回客户端本地时区时间
包含毫秒级精度(1970年1月1日至今的毫秒数)
自动处理闰秒和夏令时(根据系统设置)
性能测试:
// 100万次创建测试(Chrome 120)
console.time('Date');
for(let i=0; i<1e6; i++) new Date();
console.timeEnd('Date'); // 约120ms
2. 时间戳获取的3种方式// 方法1: Date.now() (ES5+ 推荐)
const ts1 = Date.now(); // 1715761845123
// 方法2: new Date().getTime()
const ts2 = new Date().getTime(); // 同上
// 方法3: +new Date() (类型转换)
const ts3 = +new Date(); // 同上
// 性能对比(1000万次操作)
// Date.now(): 15ms
// getTime(): 32ms
// +new Date(): 38ms适用场景:
记录操作时间戳(如日志系统)
计算代码执行耗时
生成唯一ID(结合随机数)
3. ISO 8601标准格式const isoString = new Date().toISOString();
console.log(isoString); // "2024-05-15T06:30:45.123Z"关键点:
始终返回UTC时区
末尾的Z表示零时区
适合跨时区数据传输(如API通信)
4. 本地化时间字符串// 基础本地格式
console.log(new Date().toLocaleString());
// 中文环境: "2024/5/15 下午2:30:45"
// 英文环境: "5/15/2024, 2:30:45 PM"
// 高级定制
const options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: 'Asia/Shanghai'
};
console.log(new Date().toLocaleString('zh-CN', options));
// "2024年5月15日星期三 14:30"
5. UTC时间组件获取const date = new Date();
console.log({
utcYear: date.getUTCFullYear(), // 2024
utcMonth: date.getUTCMonth() + 1, // 5 (0-11)
utcDate: date.getUTCDate(), // 15
utcDay: date.getUTCDay(), // 3 (星期三)
utcHours: date.getUTCHours(), // 6
utcMinutes: date.getUTCMinutes() // 30
});典型应用:
构建全球同步的倒计时
跨时区会议系统
国际物流跟踪
二、现代浏览器扩展API
6. Intl.DateTimeFormat高级格式化const formatter = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
timeZone: 'Asia/Shanghai'
});
console.log(formatter.format(new Date()));
// "2024/05/15 14:30:45"优势:
支持200+语言区域(如ar-EG阿拉伯语)
自动处理本地化格式(如日期分隔符)
性能优于手动字符串拼接
7. Performance API高精度时间// 获取页面加载至今的时间(微秒级)
const loadTime = performance.now(); // 1234.567890123
// 获取当前时间戳(与Date.now()精度相同)
const perfTimestamp = performance.timeOrigin + performance.now();适用场景:
精确测量动画帧时间
监控代码执行性能
防篡改的时间记录
8. Web Crypto API随机时间值// 生成加密安全的随机时间偏移(伪用例)
async function getSecureTime() {
const array = new Uint32Array(1);
await crypto.getRandomValues(array);
return Date.now() + (array[0] % 1000); // 添加随机毫秒
}安全提示:仅用于需要防篡改的时间场景,非通用时间获取方案。
三、第三方库解决方案
9. Day.js(轻量级首选)// 安装: npm install dayjs
const dayjs = require('dayjs');
// 当前时间
console.log(dayjs().format('YYYY-MM-DD HH:mm:ss'));
// "2024-05-15 14:30:45"
// 时区支持(需插件)
require('dayjs/plugin/timezone');
require('dayjs/plugin/utc');
dayjs.extend(require('dayjs/plugin/timezone'));
console.log(dayjs().tz('Asia/Shanghai').format());优势:
仅2KB包体积
100% Moment.js兼容API
支持Tree-shaking
10. Luxon(现代企业级)// 安装: npm install luxon
const { DateTime } = require('luxon');
// 当前时间
console.log(DateTime.now().toISO()); // "2024-05-15T06:30:45.123+00:00"
// 复杂操作
console.log(DateTime.now()
.setZone('Asia/Shanghai')
.plus({ days: 1 })
.toFormat('yyyy-MM-dd HH:mm'));
// "2024-05-16 14:30"特性:
内置完整时区数据库
不可变对象设计
强大的日历计算能力
11. date-fns(模块化方案)// 安装: npm install date-fns
const { format, formatISO } = require('date-fns');
// 当前时间格式化
console.log(format(new Date(), 'yyyy-MM-dd HH:mm:ss'));
// "2024-05-15 14:30:45"
// ISO格式
console.log(formatISO(new Date())); // "2024-05-15T06:30:45.123Z"模块化优势:
按需引入功能(如仅需format可节省90%体积)
纯函数设计
支持TypeScript
四、格式化输出全攻略
12. 基础日期格式化function formatDate(date = new Date(), separator = '-') {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return [year, month, day].join(separator);
}
console.log(formatDate()); // "2024-05-15"
13. 完整日期时间格式化function formatDateTime(date = new Date(), options = {}) {
const {
dateSeparator = '-',
timeSeparator = ':',
showSeconds = true
} = options;
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 = showSeconds ?
String(date.getSeconds()).padStart(2, '0') : '';
const datePart = [year, month, day].join(dateSeparator);
const timePart = [hours, minutes, seconds].filter(Boolean).join(timeSeparator);
return `${datePart} ${timePart}`;
}
console.log(formatDateTime(new Date(), { showSeconds: false }));
// "2024-05-15 14:30"
14. 中文友好格式function formatChineseDate(date = new Date(), showWeek = false) {
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
const base = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
return showWeek ? `${base} 星期${weekdays[date.getDay()]}` : base;
}
console.log(formatChineseDate(new Date(), true));
// "2024年5月15日 星期三"
15. 12小时制格式化function format12Hour(date = new Date()) {
let hours = date.getHours();
const ampm = hours >= 12 ? '下午' : '上午';
hours = hours % 12 || 12;
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${ampm} ${hours}:${String(date.getMinutes()).padStart(2, '0')}`;
}
console.log(format12Hour(new Date())); // "2024-5-15 下午2:30"
16. 相对时间格式化function timeAgo(date = new Date()) {
const seconds = Math.floor((new Date() - date) / 1000);
if (seconds < 60) return `${seconds}秒前`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}分钟前`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}小时前`;
if (seconds < 172800) return '昨天';
if (seconds < 2592000) return `${Math.floor(seconds / 86400)}天前`;
return formatDate(date);
}
console.log(timeAgo(new Date(Date.now() - 3600000))); // "1小时前"
五、性能优化与最佳实践
17. 避免频繁创建Date对象// 错误示例
function logTimeBad() {
for (let i = 0; i < 1000; i++) {
console.log(new Date().toISOString()); // 每次循环创建新对象
}
}
// 优化方案
function logTimeGood() {
const now = new Date();
for (let i = 0; i < 1000; i++) {
console.log(now.toISOString()); // 复用同一对象
}
}
18. 选择合适的时间精度// 高精度场景(如动画)
const startTime = performance.now();
// 普通日志场景
const logTime = Date.now();
// 用户显示场景
const displayTime = new Date().toLocaleTimeString();
19. 时区处理策略// 方案1:统一使用UTC(推荐)
function getUtcTime() {
return new Date().toISOString().replace('T', ' ').replace('Z', '');
}
// 方案2:用户本地时区
function getLocalTime() {
return new Date().toLocaleString('zh-CN', {
timeZone: 'Asia/Shanghai'
});
}
// 方案3:服务端传递时区信息
// 前端根据响应中的timezone字段处理
六、特殊场景解决方案
20. 处理IE兼容性问题// IE不支持Date.now()的替代方案
const ieSafeTimestamp = new Date().getTime();
// IE的toISOString兼容实现
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function() {
function pad(n) { return n < 10 ? '0' + n : n; }
return this.getUTCFullYear() + '-' +
pad(this.getUTCMonth() + 1) + '-' +
pad(this.getUTCDate()) + 'T' +
pad(this.getUTCHours()) + ':' +
pad(this.getUTCMinutes()) + ':' +
pad(this.getUTCSeconds()) + '.' +
(this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';
};
}
21. 夏令时处理// 使用Luxon自动处理夏令时
const { DateTime } = require('luxon');
console.log(DateTime.fromISO('2024-03-10T02:00:00', { zone: 'America/New_York' }).offset);
// -4 (夏令时开始)
console.log(DateTime.fromISO('2024-11-03T02:00:00', { zone: 'America/New_York' }).offset);
// -5 (夏令时结束)
22. 日期有效性验证function isValidDate(dateString) {
const date = new Date(dateString);
return !isNaN(date.getTime());
}
console.log(isValidDate('2024-02-30')); // false
console.log(isValidDate('2024-02-29')); // true (闰年)
23. 闰年判断function isLeapYear(year) {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
console.log(isLeapYear(2024)); // true
console.log(isLeapYear(2100)); // false
结语
JavaScript时间处理已形成从原生API到专业库的完整生态。对于简单需求,Date对象配合原生格式化方法即可满足;复杂国际化应用推荐使用Intl.DateTimeFormat或Luxon;需要极致轻量的场景可选择Day.js。根据2024年前端性能优化报告,合理选择时间处理方案可减少30%以上的日期相关计算开销。掌握本文提供的25种格式化模式,能覆盖90%以上的业务场景需求。
JavaScript
当前时间
本文由@战地网 原创发布。
该文章观点仅代表作者本人,不代表本站立场。本站不承担相关法律责任。
如若转载,请注明出处:https://www.zhanid.com/biancheng/4964.html
THE END
战地网
频繁记录吧,生活的本意是开心
关注