咨询day.js Localized Formats实际应用示例:多语言格式差异演示
Day.js 本地化格式多语言实操示例
前置准备
先安装核心包和需要的语言包:
npm install dayjs # 按需安装目标语言包,比如中文、日文、西班牙文 npm install dayjs/locale/zh-cn dayjs/locale/ja dayjs/locale/es
多语言场景代码示例
以下均以时间 2024-05-20 14:30:00 为例,展示不同语言下本地化格式(L/LL/LLL/LLLL)的实际效果:
1. 英文(默认)
const dayjs = require('dayjs') const targetDate = dayjs('2024-05-20 14:30:00') console.log('L 格式:', targetDate.format('L')) // 05/20/2024 console.log('LL 格式:', targetDate.format('LL')) // May 20, 2024 console.log('LLL 格式:', targetDate.format('LLL')) // May 20, 2024 2:30 PM console.log('LLLL 格式:', targetDate.format('LLLL')) // Monday, May 20, 2024 2:30 PM
2. 简体中文
const dayjs = require('dayjs') require('dayjs/locale/zh-cn') const targetDate = dayjs('2024-05-20 14:30:00').locale('zh-cn') console.log('L 格式:', targetDate.format('L')) // 2024/05/20 console.log('LL 格式:', targetDate.format('LL')) // 2024年5月20日 console.log('LLL 格式:', targetDate.format('LLL')) // 2024年5月20日下午2点30分 console.log('LLLL 格式:', targetDate.format('LLLL')) // 2024年5月20日星期一 下午2点30分
3. 日文
const dayjs = require('dayjs') require('dayjs/locale/ja') const targetDate = dayjs('2024-05-20 14:30:00').locale('ja') console.log('L 格式:', targetDate.format('L')) // 2024/05/20 console.log('LL 格式:', targetDate.format('LL')) // 2024年5月20日 console.log('LLL 格式:', targetDate.format('LLL')) // 2024年5月20日 14:30 console.log('LLLL 格式:', targetDate.format('LLLL')) // 2024年5月20日 月曜日 14:30
4. 西班牙文
const dayjs = require('dayjs') require('dayjs/locale/es') const targetDate = dayjs('2024-05-20 14:30:00').locale('es') console.log('L 格式:', targetDate.format('L')) // 20/05/2024 console.log('LL 格式:', targetDate.format('LL')) // 20 de mayo de 2024 console.log('LLL 格式:', targetDate.format('LLL')) // 20 de mayo de 2024 14:30 console.log('LLLL 格式:', targetDate.format('LLLL')) // lunes, 20 de mayo de 2024 14:30
核心逻辑总结
L/LL/LLL/LLLL这些占位符的格式规则,由对应语言包预先定义,无需手动编写日期字符串- 用
locale('语言编码')切换单实例语言,或dayjs.locale('语言编码')设置全局默认语言 - 若需自定义某语言的本地化格式,可通过
dayjs.extend()扩展修改
内容的提问来源于stack exchange,提问作者TinyTiger
相关产品推荐
相关产品推荐

