一、常用日期格式化方法
// 1. 使用Date對象toLocaleString()方法進行格式化
let date = new Date();
let strDate = date.toLocaleString(); // 2022/1/5 下午2:05:21
// 2. 使用Intl.DateTimeFormat()方法進行格式化
let date = new Date();
let options = { year: 'numeric', month: 'long', day: 'numeric' };
let formatter = new Intl.DateTimeFormat('zh-cn', options);
let strDate = formatter.format(date); // 2022年1月5日
// 3. 使用moment.js庫進行格式化
import moment from 'moment';
let date = new Date();
let strDate = moment(date).format('YYYY年MM月DD日'); // 2022年01月05日
在Vue中,我們通常使用第三種方法,即使用moment.js庫進行日期格式化。它使用起來方便簡單,且支持多種語言、時區等功能。
二、Vue過濾器中的日期格式化
// main.js中引入moment.js庫
import moment from 'moment';
Vue.prototype.$moment = moment;// 在Vue過濾器中使用
Vue.filter('formatDate', function(value, formatStr) {
if (!value) return '';
return moment(value).format(formatStr);
});
// 在組件中使用
{{ date | formatDate('YYYY年MM月DD日') }}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/207163.html