使用moment.js解決前端專案開發上的時間及日期的使用需求。

moment.js 是一個輕量級的 JavaScript 日期庫,用於解析,驗證,操作和格式化日期。

# 安裝
1
2
npm install moment --save   # npm
yarn add moment # Yarn
# 使用
  • Format Dates
1
2
3
4
5
moment().format("MMMM Do YYYY, h:mm:ss a"); // October 21st 2019, 4:30:21 pm
moment().format("dddd"); // Monday
moment().format("MMM Do YY"); // Oct 21st 19
moment().format("YYYY [escaped] YYYY"); // 2019 escaped 2019
moment().format(); // 2019-10-21T16:30:21+08:00
  • Calendar Time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
moment()
.subtract(10, "days")
.calendar(); // 10/11/2019
moment()
.subtract(6, "days")
.calendar(); // Last Tuesday at 4:32 PM
moment()
.subtract(3, "days")
.calendar(); // Last Friday at 4:32 PM
moment()
.subtract(1, "days")
.calendar(); // Yesterday at 4:32 PM
moment().calendar(); // Today at 4:32 PM
moment()
.add(1, "days")
.calendar(); // Tomorrow at 4:32 PM
moment()
.add(3, "days")
.calendar(); // Thursday at 4:32 PM
moment()
.add(10, "days")
.calendar(); // 10/31/2019

# 搭配 vue.js + moment 完成時間快捷選項
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<template>
<div class="block">
<span class="demonstration">快捷選項</span>
<el-date-picker
v-model="dateRange"
type="monthrange"
align="right"
unlink-panels
range-separator="至"
start-placeholder="開始月份"
end-placeholder="結束月份"
:picker-options="pickerOptions">
</el-date-picker>
</div>
</template>

<script>
export default {
data: ()=> ({
dateRange: [moment().startOf("month"), moment().endOf("month")],
pickerOptions: {
shortcuts: [
{
text: "最近一週",
onClick(picker) {
let start = moment().startOf("week");
let end = moment().endOf("week");
picker.$emit("pick", [start, end]);
}
},
{
text: "最近一個月",
onClick(picker) {
let start = moment().startOf("month");
let end = moment().endOf("month");
picker.$emit("pick", [start, end]);
}
},
{
text: "上一個月",
onClick(picker) {
let start = moment()
.startOf("month")
.subtract(1, "month");
let end = moment()
.endOf("month")
.subtract(1, "month");
picker.$emit("pick", [start, end]);
}
},
{
text: "最近三個月",
onClick(picker) {
let start = moment()
.startOf("month")
.subtract(2, "month");
let end = moment().endOf("month");
picker.$emit("pick", [start, end]);
}
}
]
}
}),
watch: {
dateRange:"changeRangeInfo"
},
methods: {
changeSearchInfo(info) {
const { dateRange } = this;
const startAt = moment(dateRange[0]).format("YYYY-MM-DD, 00:00:00");
const endAt = moment(dateRange[1]).format("YYYY-MM-DD, 23:59:59");
console.log({startAt,endAt})
}
}
};
</script>

1
2
// 最近一週
{startAt: "2019-10-20, 00:00:00", endAt: "2019-10-26, 23:59:59"}
1
2
// 最近一個月
{startAt: "2019-10-01, 00:00:00", endAt: "2019-10-31, 23:59:59"}
1
2
// 上一個月
{startAt: "2019-09-01, 00:00:00", endAt: "2019-09-30, 23:59:59"}
1
2
// 最近三個月
{startAt: "2019-08-01, 00:00:00", endAt: "2019-10-31, 23:59:59"}