This is the fifth day of my participation in the August More text Challenge. For details, see:August is more challenging

Introduction:

Moment.js is a lightweight JavaScript date-processing library that is easy to use, providing date formatting, date parsing, and more. It supports running in both the browser and NodeJS environments. This type of library can be given any date into a variety of different formats, with powerful date calculation capabilities, but also built-in functions can display a variety of date forms. In addition, it also supports multiple languages, so you can add any new language pack you want.

Moment.js provides a rich API for users. We can process the data through the CORRESPONDING API to get the results we want.

Here are some examples of simple use of common apis:

  • Initialization of time type data

Initialization date:

    moment().format('YYYY-MM-DD');
Copy the code

Initialization date and time:

    moment().format('YYYY-MM-DD HH:mm:ss');
Copy the code
  • Time plus/minus

    You must use this.moment(date variable) before you operate; Convert the date to a date-time format that moment.js can handle.

Add (current date plus one month with output format ‘YYYY-MM-DD’)

    this.moment().add(1.'months').format('YYYY-MM-DD'); 
Copy the code

Subtraction (current time minus 3 days)

    this.moment().subtract(3.'days');
Copy the code
  • Get the first or last day of a month or year

Get the first day of a year: startOf(‘year’)

My moment (date). StartOf ('year').format("YYYY-MM-DD")
Copy the code

Get the first day of a month: startOf(‘month’)

My moment (date). StartOf ('month').format("YYYY-MM-DD")
Copy the code

Get the last day of a year: endOf(‘year’)

The moment (date). The endOf ('year').format("YYYY-MM-DD")
Copy the code

Get the last day of a month: endOf(‘month’)

The moment (date). The endOf ('month').format("YYYY-MM-DD")
Copy the code
  • Get time difference (in milliseconds)

The time difference between the start time and the end time is in days. Both endTime and startTime are milliseconds

    this.moment(endTime).diff(this.moment(startTime),'days' )
Copy the code

The time difference between the start time and the end time is in minutes

    this.moment(endTime).diff(this.moment(startTime), 'minutes')
Copy the code

When calculating the time difference, the output can be “years”, “days”, “hours”, “minutes”, or “seconds”.

I’m just going to mention so many common apis. If you have other needs, you can go to the moment.js website to find the answer.

Note: moment() can be passed as an argument. If you don’t pass it, it defaults to the current time. If you pass it, it will be formatted with the passed time as the target time