JavaScript日期格式化首选Intl.DateTimeFormat,因其支持国际化、自定义选项丰富且性能佳;对于特殊格式需求可手动拼接,解析日期字符串时应优先使用ISO 8601标准格式以确保兼容性和时区正确性。

在JavaScript中处理日期格式化,说起来简单,但真要做到灵活且兼顾国际化,还是有不少门道的。核心思路无非两种:一是利用JS内置的
Date
Intl
Intl.DateTimeFormat
要搞定JS日期格式化,我们通常有以下几种方式,从基础到高级,各有侧重:
手动拼接: 这是最原始也最直接的方法。通过
Date
getFullYear()
getMonth()
getDate()
getHours()
getMinutes()
getSeconds()
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} ${hours}:${minutes}:${seconds}`;
console.log(formattedDate); // 输出类似 "2023-10-27 10:30:45"这种方式胜在完全可控,但代码量稍大,且需要手动处理月份加一和数字补零的问题。
Date
toLocaleString()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
locales
options
const now = new Date();
// 默认本地格式
console.log(now.toLocaleString()); // 比如 "2023/10/27 上午10:30:45" (取决于浏览器设置)
// 指定语言和选项
console.log(now.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric'
})); // "2023年10月27日"
console.log(now.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false // 24小时制
})); // "10:30:45"这组方法的好处是能自动处理国际化,但自定义格式的灵活性相对有限,你只能在预设的几种样式中选择。
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/27 10:30:45"
// 更多自定义,例如显示星期几和时区
const formatterWithWeekday = new Intl.DateTimeFormat('en-US', {
weekday: 'long',
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZoneName: 'short', // 显示时区缩写
timeZone: 'Asia/Shanghai' // 指定时区
});
console.log(formatterWithWeekday.format(now)); // "Friday, Oct 27, 2023, 10:30 AM CST" (示例,具体取决于当前时间)Intl.DateTimeFormat
locale
第三方库: 像
date-fns
Luxon
date-fns
format
// 需要安装:npm install date-fns
import { format } from 'date-fns';
const now = new Date();
console.log(format(now, 'yyyy-MM-dd HH:mm:ss')); // "2023-10-27 10:30:45"我个人倾向于在非必要时少引入外部库,但如果项目中有大量日期操作,或者对旧浏览器兼容性有较高要求,这些库确实能提供很好的解决方案。
说真的,有时候内置的
toLocaleString
Intl.DateTimeFormat
最直接的方法就是利用
Date
get
Intl.DateTimeFormat
function formatCustomDate(date) {
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 = String(date.getSeconds()).padStart(2, '0');
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekday = weekdays[date.getDay()]; // getDay() 返回0-6,对应星期日到星期六
return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds} ${weekday}`;
}
const myDate = new Date();
console.log(formatCustomDate(myDate)); // 示例输出: "2023年10月27日 10:30:45 星期五"这种方法虽然需要写更多的代码来处理补零和数组映射(比如星期几),但它的好处是显而易见的:你完全掌控了输出的每一个字符。当你面对一些特别奇葩的日期格式需求时,比如"2023/10/27 (周五) 上午10点半",用
Intl.DateTimeFormat
getUTC...
当我第一次接触
Intl.DateTimeFormat
options
Intl.DateTimeFormat
options
weekday
long
short
narrow
year
numeric
2-digit
month
numeric
2-digit
long
short
narrow
day
numeric
2-digit
hour
numeric
2-digit
minute
numeric
2-digit
second
numeric
2-digit
timeZoneName
long
short
timeZone
'America/New_York'
'Asia/Shanghai'
hour12
true
false
hourCycle
h11
h12
h23
h24
formatMatcher
basic
best fit
国际化实践中的几个点:
明确指定locale
'zh-CN'
'en-US'
const eventTime = new Date('2024-01-01T14:30:00Z'); // UTC时间
// 为中国用户显示
const chinaFormatter = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: 'Asia/Shanghai', // 指定上海时区
hour12: false
});
console.log(`中国时间: ${chinaFormatter.format(eventTime)}`); // 示例: 中国时间: 2024年1月1日 下午10:30 (因为UTC+8)
// 为美国纽约用户显示
const nyFormatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZone: 'America/New_York', // 指定纽约时区
hour12: true
});
console.log(`纽约时间: ${nyFormatter.format(eventTime)}`); // 示例: 纽约时间: Jan 1, 2024, 9:30 AM (因为UTC-5)这个例子清楚地展示了
timeZone
formatToParts()
Intl.DateTimeFormat
formatToParts()
const parts = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).formatToParts(new Date());
console.log(parts);
// 示例输出:
// [
// { type: 'month', value: '10' },
// { type: 'literal', value: '/' },
// { type: 'day', value: '27' },
// { type: 'literal', value: '/' },
// { type: 'year', value: '2023' }
// ]通过这个方法,你可以拿到一个包含日期时间各部分类型和值的数组,这为更高级的自定义渲染提供了可能性,比如在UI中高亮显示某个部分。
总之,
Intl.DateTimeFormat
在实际开发中,我们经常会遇到这样的场景:从后端API获取到一个日期字符串,或者用户在输入框里填了一个日期,然后我们需要把这个字符串转换成JavaScript的
Date
最常见的转换方式是直接使用
new Date(dateString)
Date.parse(dateString)
const dateString1 = "2023-10-27T10:30:00Z"; // ISO 8601 格式,带时区信息 const date1 = new Date(dateString1); console.log(date1); // 正常解析,得到一个Date对象 const dateString2 = "2023-10-27 10:30:00"; // 常见但非标准格式 const date2 = new Date(dateString2); console.log(date2); // 某些浏览器可能解析失败或解析结果不一致
常见问题:
浏览器兼容性问题: 这是最让人头疼的一点。
new Date(string)
"YYYY-MM-DD"
"MM/DD/YYYY"
"YYYY/MM/DD HH:mm:ss"
Invalid Date
"2023-10-27"
"2023/10/27"
时区问题: 如果日期字符串不包含时区信息(例如
"2023-10-27 10:30:00"
new Date()
解决方案:
始终使用ISO 8601格式: 这是处理日期字符串解析的黄金法则。ISO 8601格式(如
"YYYY-MM-DDTHH:mm:ss.sssZ"
"YYYY-MM-DDTHH:mm:ss.sss±HH:MM"
const isoString = "2023-10-27T10:30:00.000Z"; // UTC时间 const dateFromIso = new Date(isoString); console.log(dateFromIso); // 总是能正确解析为UTC时间 const isoStringLocal = "2023-10-27T10:30:00"; // 不带Z,会被解析为本地时间 const dateFromIsoLocal = new Date(isoStringLocal); console.log(dateFromIsoLocal); // 解析为本地时间
如果字符串带有
Z
手动解析非标准格式: 如果你无法控制日期字符串的来源(比如从用户输入或遗留系统),并且它不是ISO 8601格式,那么最稳妥的办法就是手动解析它。这意味着你需要自己编写代码来根据已知的格式规则,从字符串中提取年、月、日、时、分、秒等信息,然后使用
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds)
Date
function parseCustomDateString(dateString) {
// 假设格式是 "YYYY/MM/DD HH:mm:ss"
const parts = dateString.match(/(\d{4})\/(\d{2})\/(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
if (parts) {
// 注意:月份在Date构造函数中是0-11
return new Date(
parseInt(parts[1]), // 年
parseInt(parts[2]) - 1, // 月 (减1)
parseInt(parts[3]), // 日
parseInt(parts[4]), // 时
parseInt以上就是JS日期格式化怎么做的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号