關於日期,咱們常常添加大型庫(例如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" 複製代碼