当前位置:网站首页>Moment time plug-in tips -js (super detailed)

Moment time plug-in tips -js (super detailed)

2022-06-11 06:27:00 Э Time walker to me

Let's share one moment Plug in tips

1. This month, ( The current month )YYYY-MM

eg:2022-01----2022-01

notes :this.$moment() Is my main.js Overall , You can also introduce... On demand

moment

import Moment from 'moment'
Vue.prototype.$moment = Moment
let date1 = this.$moment().startOf('month').format('yyyy-MM')
let date2 = this.$moment().endOf('month').format('yyyy-MM')

2. This month, + date YYYY-MM-DD

For example, in January 1 The start , End on current date

eg:2022-01-01----2022-01-20

moment

let date1 = this.$moment(new Date()).startOf('month').format('YYYY-MM-DD')
let date2 = this.$moment(new Date()).format('YYYY-MM-DD')

Abbreviation , Negligible new Date()

let date1 = this.$moment().startOf('month').format('YYYY-MM-DD')
let date2 = this.$moment().format('YYYY-MM-DD')

3. This year YYYY-MM

For example, in January of this year 1 The start , To the current year 12 End of the month

eg:2022-01----2022-12

moment

let date1 = this.$moment().startOf('year').format('yyyy-MM')
let date2 = this.$moment().endOf('year').format('yyyy-MM')

4. This year YYYY-MM-DD

For example, in January of this year 1 The start , To the current year 12 month 31 End of the day

eg:2022-01-01----2022-12-31

moment

let date1 = this.$moment().startOf('year').format('yyyy-MM-DD')
let date2 = this.$moment().endOf('year').format('yyyy-MM-DD')

5. The first seven days YYYY-MM-DD

For example, the first seven days of this month

With 20 Column No eg:2022-01-13----2022-01-20

let date1 = this.$moment(new Date()).subtract(7, 'days').format('YYYY-MM-DD')
let date2 = this.$moment(new Date()).format('YYYY-MM-DD')

6. front 30 God 、 front 60 God 、 front 90 The sky is the same YYYY-MM-DD

According to your own needs , You can also write before 2 Months 、 front 3 Months …

moment

front 60 Heaven and earth 20 Column No eg:2021-11-21----2022-01-20

let date1 = this.$moment(new Date()).subtract(60, 'days').format('YYYY-MM-DD')
let date2 = this.$moment(new Date()).format('YYYY-MM-DD')

7. Calculate the number of days between two times

moment

Be careful : The date must be big or small , Otherwise the date will become negative , Unless you need to count down And so on. , That's OK

let startDate = moment('2022-01-01 09:00').format('YYYY-MM-DD')
let endDate = moment('2022-02-01 09:00').format('YYYY-MM-DD')
console.log(' The difference in days is 1-------->', moment(endDate).diff(startDate, 'day')) // 31 God 
//  Or you can write the following method in one step 
let date1 = this.moment('2022-02-01 09:00').diff(this.moment('2022-01-01 09:00'), 'day', true).toFixed(1)
console.log(' The difference in days is 2-------->', date1 ) // 31.0  You can see whether you need a decimal point according to your own needs 
原网站

版权声明
本文为[Э Time walker to me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020527312449.html