一、自己封裝date pipe
創建date.pipe.js
export function datePipe(timestamp, format = 'yyyy-MM-dd hh:mm:ss') {
let date = new Date(timestamp);
var o = {
'y+': date.getFullYear(),
'M+': date.getMonth() + 1, // 月份 "d+": value.getDate(), // 日
'd+': date.getDate(),
'h+': date.getHours(), // 小時 "m+": value.getMinutes(), // 分 "s+": value.getSeconds(), // 秒
'm+': date.getMinutes(),
's+': date.getSeconds()
};
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(format)) {
format = format.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
);
}
}
return format;
}
在main.js
引入
import { datePipe } from './core/pipes/date.pipe';
Vue.filter('date', datePipe);
使用:
<div>{{item.create_time | date('yyyy-MM-dd hh:mm')}}</div>
安裝 Day.js :一個輕量的處理時間和日期的 JavaScript 庫
安裝
NPM:
npm install dayjs --save
import dayjs from 'dayjs'
// 或者 CommonJS
// var dayjs = require('dayjs');
dayjs().format();
CDN:
<!-- 最新的壓縮后的 JavaScript 文件 -->
<script src="https://unpkg.com/dayjs"></script>
<script>
dayjs().format();
</script>
API參考:
- 當前時間
dayjs() - 時間字符串
dayjs('2018-06-03') - 時間戳
dayjs(1528361259484) - Date 對象
dayjs(new Date(2018,8,18)) - 復制
dayjs().clone() - 檢測當前 Dayjs 對象是否是一個有效的時間
dayjs().isValid() - 獲取
年 : dayjs().year()
月 : dayjs().month()
日 : dayjs().date()
星期 : dayjs().day()
時 : dayjs().hour()
分 : dayjs().minute()
秒 : dayjs().second()
毫秒 : dayjs().millisecond() - 設置
dayjs().set('year',2017)
dayjs().set('month',9) - 增加時間并返回一個新的 Dayjs() 對象
dayjs().add(7, 'day')
dayjs().add(7, 'year') - 減少時間并返回一個新的 Dayjs() 對象
dayjs().subtract(7, 'year')
dayjs().subtract(7, 'month') - 返回當前時間的開頭時間的 Dayjs() 對象,如月份的第一天。
dayjs().startOf('year')
dayjs().startOf('month') - 返回當前時間的末尾時間的 Dayjs() 對象,如月份的最后一天。
dayjs().endOf('month')
dayjs().endOf('year') - 格式化
dayjs().format()
dayjs().format('YYYY-MM-DD dddd HH:mm:ss.SSS A') - 時間差
dayjs('2018-06-08').diff(dayjs('2017-06-01'),'years')
dayjs('2018-06-08').diff(dayjs('2017-06-01'),'day')
dayjs('2018-06-08').diff(dayjs('2017-06-01'),'hour') - Unix 時間戳 (毫秒)
dayjs().valueOf() - Unix 時間戳 (秒)
dayjs().unix() - 返回月份的天數
dayjs().daysInMonth() - 返回原生的 Date 對象
dayjs().toDate() - 返回包含時間數值的數組
dayjs().toArray() - 當序列化 Dayjs 對象時,會返回 ISO8601 格式的字符串
dayjs().toJSON() //2018-06-08T02:44:30.599Z - 返回 ISO8601 格式的字符串
dayjs().toISOString() //2018-06-08T02:46:06.554Z
-返回包含時間數值的對象
dayjs().toObject() - 字符串
dayjs().toString() - 檢查一個 Dayjs 對象是否在另一個 Dayjs 對象時間之前
dayjs('2018-06-01').isBefore(dayjs('2018-06-02')) - 檢查一個 Dayjs 對象是否和另一個 Dayjs 對象時間相同
dayjs().isSame(dayjs()) - 檢查一個 Dayjs 對象是否在另一個 Dayjs 對象時間之后
dayjs().isAfter(dayjs())