关于日期,咱们常常添加大型库(例如Moment.js或Day.Js)来格式化简单的日期。但这实际上比使用该toLocalDateString()方法简单得多,不只能在Date上,在Number也能发挥的它的做用html
我收录了关于时间处理的插件,如今比较流行使用的git
时间处理插件数据库
toLocaleDateString
方法返回该日期对象日期部分的字符串,该字符串格式因不一样语言而不一样。新增的参数 locales 和 options 使程序可以指定使用哪一种语言格式化规则,容许定制该方法的表现(behavior)。浏览器
在旧版本浏览器中, locales 和 options 参数被忽略,使用的语言环境和返回的字符串格式是各自独立实现的markdown
❝关于兼容性插件MDNoop
❞
Date.prototype.toLocaleDateString()ui
Date 实例转为表示本地时间的字符串,有常见三种方法spa
new Date().toLocaleTimeString() // "下午12:26:15"
new Date().toLocaleDateString() // "2020/10/18" new Date().toLocaleString() // "2020/10/18 下午12:26:24" 复制代码
这三个方法都有两个可选的参数prototype
new Date().toLocaleString([locales[, options]])
new Date().toLocaleDateString([locales[, options]]) new Date().toLocaleTimeString([locales[, options]]) 复制代码
这两个参数中,locales是一个指定所用语言的字符串,options是一个配置对象插件
我是在Vue环境中使用的
<p>{{formatDate('2020/10/18')}}</p>
复制代码
结果: 2020年10月18日
formatDate(date) {
const options = { year: 'numeric', month: 'long', day: 'numeric' } return new Date(date).toLocaleDateString('zh-CN', options) } 复制代码
<p>{{formatDate('2020/10/18')}}</p>
复制代码
结果: 2020年10月18日星期日
formatDate(date) {
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } return new Date(date).toLocaleDateString('zh-CN', options) } 复制代码
<p>{{formatDate('2020/10/18')}}</p>
复制代码
结果: Sunday, October 18, 2020
formatDate(date) {
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' } return new Date(date).toLocaleDateString('en-US', options) } 复制代码
options
new Date().toLocaleDateString('zh-CN', {
weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }) // "2020年10月18日星期日" new Date().toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false, timeZoneName: 'long' }) // "中国标准时间 12:20:18" new Date().toLocaleTimeString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: true, day: 'numeric' }) // "18日 下午12:21:29" 复制代码
在Number的原型上也有这个方法toLocaleString
,即Number.prototype.toLocaleString()
const price = 12345678;
price.toLocaleString(); // => "12,345,678" 复制代码
currency 单位列表,查看
var price = 2499;
price.toLocaleString('zh-CN', { style: 'currency', currency: 'RMB' }); // "RMB 2,499.00" var price = 2499; price.toLocaleString('zh-CN', { style: 'currency', currency: 'USD' }); // "US$2,499.00" 复制代码
var price = 2499;
price.toLocaleString('zh-CN', { style: 'currency', currency: 'KNS', minimumFractionDigits:3 }); // "KNS 2,499.000" 复制代码