[note] dayjs 筆記
顯示時間(Display)
基本 format
import dayjs from 'dayjs';
const now = dayjs();
const format = now.format('DD/MM/YYYY'); // 07/08/2020
Time from X
- 需要使用
relativeTime
這個 plugin
import dayjs from 'dayjs';
// 使用 relativeTime plugin
import relativeTime from 'dayjs/plugin/relativeTime';
dayjs.extend(relativeTime);
const anHourAgo = dayjs().subtract(1, 'hour');
const timeFromNow = anHourAgo.fromNow(); // an hour ago
Difference
取得兩個時間點之間的長度。
date1.diff('2018-06-05', <unit: string>, <float: bool>)
- 在
diff
的第二個參數可以放入要取得單位,預設是毫秒 - 在
diff
的第三個參數可以決定要不要顯示到小數點後位數
⚠️ 留意:如果要計算的是兩個時間點的間隔長度,而且需要取得多個時間單位,則要搭配使用
days#duration
這個 plugin。
import dayjs from 'dayjs';
const date1 = dayjs('2019-01-25');
const date2 = dayjs('2018-06-05');
const diffWithMS = date1.diff(date2); // 預設會顯示到毫秒,20214000000 default milliseconds
const diffWithMonth = date1.diff(date2, 'month'); // 7
i18n
使用 locale 檔
import 'dayjs/locale/zh-tw';
import dayjs from 'dayjs';
dayjs.locale('zh-tw'); // use locale
const formatLocale = dayjs('2019-01-25').format('DD/MMM/YYYY 星期dd'); // 25/1月/2019 星期五