前言
在 JS 中,处理时间和日期是常见的需求。无论是展示当前时间、格式化日期字符串,还是进行时间计算,JavaScript 都提供了丰富的 API 来满足这些需求。本文将详细介绍如何使用 JavaScript 生成各种时间格式,从基础到高级,涵盖常见的场景。内容比较多,请大家搭配目录食用。
基础时间获取
1.1 获取当前时间
JavaScript 提供了 Date
对象来处理日期和时间。要获取当前时间,只需创建一个 Date
对象即可:
const now = new Date(); console.log(now); // 输出当前时间的完整日期和时间
1.2 获取时间戳
时间戳表示从 1970 年 1 月 1 日 00:00:00 UTC 到当前时间的毫秒数。可以使用 getTime()
方法或 Date.now()
来获取时间戳:
const timestamp1 = new Date().getTime(); const timestamp2 = Date.now(); console.log(timestamp1, timestamp2); // 输出当前时间的时间戳
时间格式化
2.1 使用 toLocaleString() 格式化时间
toLocaleString()
方法可以根据本地化设置格式化日期和时间:
const now = new Date(); console.log(now.toLocaleString()); // 输出本地化的日期和时间 console.log(now.toLocaleDateString()); // 输出本地化的日期 console.log(now.toLocaleTimeString()); // 输出本地化的时间
2.2 自定义格式化
如果需要更灵活的格式化,可以手动拼接日期和时间的各个部分:
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1 const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; const formattedTime = `${hours}:${minutes}:${seconds}`; const formattedDateTime = `${formattedDate} ${formattedTime}`; console.log(formattedDate); // 输出格式化的日期,如 "2023-10-05" console.log(formattedTime); // 输出格式化的时间,如 "14:30:45" console.log(formattedDateTime); // 输出格式化的日期和时间,如 "2023-10-05 14:30:45"
2.3 使用 Intl.DateTimeFormat 进行高级格式化
Intl.DateTimeFormat
对象提供了更强大的本地化日期和时间格式化功能:
const now = new Date(); 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 // 使用24小时制 }); console.log(formatter.format(now)); // 输出格式化的日期和时间,如 "2023/10/05 14:30:45"
时间计算
3.1 时间加减
可以通过修改 Date
对象的各个部分来进行时间加减:
const now = new Date(); now.setHours(now.getHours() + 1); // 当前时间加1小时 now.setDate(now.getDate() + 7); // 当前日期加7天 console.log(now);
3.2 计算时间差
可以通过时间戳来计算两个时间点之间的差值:
const start = new Date('2023-10-01T00:00:00'); const end = new Date('2023-10-05T12:00:00'); const diffInMilliseconds = end - start; // 时间差,单位为毫秒 const diffInSeconds = diffInMilliseconds / 1000; const diffInMinutes = diffInSeconds / 60; const diffInHours = diffInMinutes / 60; const diffInDays = diffInHours / 24; console.log(diffInDays); // 输出时间差,如 "4.5" 天
时区处理
4.1 获取当前时区
可以使用 Intl.DateTimeFormat
获取当前时区:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(timeZone); // 输出当前时区,如 "Asia/Shanghai"
4.2 转换时区
可以使用 toLocaleString()
或 Intl.DateTimeFormat
来转换时区:
const now = new Date(); const options = { timeZone: 'America/New_York', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }; const formatter = new Intl.DateTimeFormat('en-US', options); console.log(formatter.format(now)); // 输出纽约时间,如 "10/05/2023 02:30:45"
第三方库推荐
虽然 JavaScript 原生的 Date
对象已经足够强大,但在处理复杂的日期和时间操作时,使用第三方库可以更加方便。以下是几个常用的日期处理库:
- Moment.js: 功能强大,但体积较大,推荐使用其替代品。
- Day.js: Moment.js 的轻量级替代品,API 兼容,体积小。
- date-fns: 模块化设计,按需引入,功能丰富。
// 使用 Day.js 格式化时间 const dayjs = require('dayjs'); console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // 输出格式化的日期和时间
常用的格式示例
1. 基础时间格式
const now = new Date(); // 完整日期和时间 console.log(now.toString()); // "Thu Oct 05 2023 14:30:45 GMT+0800 (China Standard Time)" // ISO 格式 console.log(now.toISOString()); // "2023-10-05T06:30:45.000Z" // 本地日期和时间 console.log(now.toLocaleString()); // "2023/10/5 14:30:45" (根据本地化设置) // 本地日期 console.log(now.toLocaleDateString()); // "2023/10/5" // 本地时间 console.log(now.toLocaleTimeString()); // "14:30:45"
2. 自定义格式化
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); // 年-月-日 console.log(`${year}-${month}-${day}`); // "2023-10-05" // 时:分:秒 console.log(`${hours}:${minutes}:${seconds}`); // "14:30:45" // 年/月/日 时:分:秒 console.log(`${year}/${month}/${day} ${hours}:${minutes}:${seconds}`); // "2023/10/05 14:30:45" // 月/日/年 console.log(`${month}/${day}/${year}`); // "10/05/2023" // 日-月-年 console.log(`${day}-${month}-${year}`); // "05-10-2023"
3. 相对时间
const now = new Date(); const past = new Date(now - 5 * 60 * 1000); // 5分钟前 const future = new Date(now + 2 * 24 * 60 * 60 * 1000); // 2天后 // 相对时间计算 function formatRelativeTime(date) { const diff = Math.round((date - now) / 1000); // 时间差(秒) if (diff < 60) return `${diff}秒${diff > 0 ? '后' : '前'}`; if (diff < 3600) return `${Math.floor(diff / 60)}分钟${diff > 0 ? '后' : '前'}`; if (diff < 86400) return `${Math.floor(diff / 3600)}小时${diff > 0 ? '后' : '前'}`; return `${Math.floor(diff / 86400)}天${diff > 0 ? '后' : '前'}`; } console.log(formatRelativeTime(past)); // "5分钟前" console.log(formatRelativeTime(future)); // "2天后"
4. 时间拼接
const now = new Date(); const year = now.getFullYear(); const month = String(now.getMonth() + 1).padStart(2, '0'); const day = String(now.getDate()).padStart(2, '0'); const hours = String(now.getHours()).padStart(2, '0'); const minutes = String(now.getMinutes()).padStart(2, '0'); const seconds = String(now.getSeconds()).padStart(2, '0'); // 拼接成文件名格式 console.log(`log_${year}${month}${day}_${hours}${minutes}${seconds}.txt`); // "log_20231005_143045.txt" // 拼接成日志格式 console.log(`[${year}-${month}-${day} ${hours}:${minutes}:${seconds}] INFO: Hello World`); // "[2023-10-05 14:30:45] INFO: Hello World"
5. 时区转换
const now = new Date(); // 转换为纽约时间 console.log(now.toLocaleString('en-US', { timeZone: 'America/New_York' })); // "10/5/2023, 2:30:45 AM" // 转换为东京时间 console.log(now.toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' })); // "2023/10/5 15:30:45"
6. 时间戳格式化
const timestamp = Date.now(); // 时间戳转日期 const date = new Date(timestamp); console.log(date.toLocaleString()); // "2023/10/5 14:30:45" // 时间戳转自定义格式 const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`; console.log(formattedDate); // "2023-10-05"
7. 高级格式化(Intl.DateTimeFormat
)
const now = new Date(); // 中文格式 console.log(new Intl.DateTimeFormat('zh-CN', { dateStyle: 'full', timeStyle: 'long' }).format(now)); // "2023年10月5日星期四 14:30:45 GMT+8" // 英文格式 console.log(new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeStyle: 'short' }).format(now)); // "Oct 5, 2023, 2:30 PM" // 自定义格式 console.log(new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }).format(now)); // "Oct 05, 2023, 02:30:45 PM"
8. 时间差计算
const start = new Date('2023-10-01T00:00:00'); const end = new Date('2023-10-05T12:00:00'); // 计算时间差(毫秒) const diff = end - start; // 转换为天、小时、分钟、秒 const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((diff % (1000 * 60)) / 1000); console.log(`${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`); // "4天 12小时 0分钟 0秒"
9. 使用第三方库(Day.js)
const dayjs = require('dayjs'); // 格式化 console.log(dayjs().format('YYYY-MM-DD HH:mm:ss')); // "2023-10-05 14:30:45" // 相对时间 console.log(dayjs().from(dayjs('2023-10-01'))); // "4天前" // 时间差 console.log(dayjs('2023-10-05').diff(dayjs('2023-10-01'), 'day')); // 4
10. 其他格式
const now = new Date(); // 12小时制 console.log(now.toLocaleString('en-US', { hour12: true })); // "10/5/2023, 2:30:45 PM" // 24小时制 console.log(now.toLocaleString('en-US', { hour12: false })); // "10/5/2023, 14:30:45" // 仅日期(短格式) console.log(now.toLocaleDateString('en-US', { dateStyle: 'short' })); // "10/5/23" // 仅时间(短格式) console.log(now.toLocaleTimeString('en-US', { timeStyle: 'short' })); // "2:30 PM"
总结
JavaScript 提供了丰富的 API 来处理日期和时间,从基础的 Date
对象到高级的 Intl.DateTimeFormat
,可以满足大多数场景的需求。通过本文的介绍,你应该能够掌握如何使用 JavaScript 生成各种时间格式,并进行时间计算和时区转换。对于更复杂的需求,可以考虑使用第三方库来简化操作。
到此这篇关于JavaScrip时间格式整理大全的文章就介绍到这了,更多相关JS时间格式大全内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源链接:https://www.jb51.net/javascript/338949g4d.htm
如有侵犯您的版权,请及时联系3500663466#qq.com(#换@),我们将第一时间删除本站数据。
暂无评论内容