对于日期,咱们常常增加大型库(例如Moment.js或Day.Js)来格式化简略的日期。但这实际上比应用该toLocalDateString()办法简略得多,不仅能在Date上,在Number也能施展的它的作用
对于工夫解决的插件
我收录了对于工夫解决的插件,当初比拟风行应用的
工夫解决插件
toLocaleDateString
toLocaleDateString
办法返回该日期对象日期局部的字符串,该字符串格局因不同语言而不同。新增的参数 locales 和 options 使程序可能指定应用哪种语言格式化规定,容许定制该办法的体现(behavior)。
在旧版本浏览器中, locales 和 options 参数被疏忽,应用的语言环境和返回的字符串格局是各自独立实现的
对于兼容性插件MDN
Date.prototype.toLocaleDateString()
Date
Date 实例转为示意本地工夫的字符串,有常见三种办法
- Date.prototype.toLocaleString():残缺的本地工夫。
- Date.prototype.toLocaleDateString():本地日期(不含小时、分和秒)。
- Date.prototype.toLocaleTimeString():本地工夫(不含年月日)
new Date().toLocaleTimeString() // "下午12:26:15"new Date().toLocaleDateString() // "2020/10/18"new Date().toLocaleString() // "2020/10/18 下午12:26:24"
这三个办法都有两个可选的参数
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
- dateStyle:可能的值为full、long、medium、short。
- timeStyle:可能的值为full、long、medium、short。
- month:可能的值为numeric、2-digit、long、short、narrow。
- year:可能的值为numeric、2-digit。
- weekday:可能的值为long、short、narrow。
- day、hour、minute、second:可能的值为numeric、2-digit。
- timeZone:可能的值为 IANA 的时区数据库。
- timeZooneName:可能的值为long、short。
- hour12:24小时周期还是12小时周期,可能的值为true、false
列子
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"