When the author was working on the project, he needed to process and operate the Date and time. However, it was very inconvenient to use the Date object of JS every time, and he also needed to write a lot of tedious codes, which made subsequent maintenance very painful. I found MomentJS plug-in for handling date and time on the Internet and found it very easy to use. After learning its syntax, I found it very simple and easy to understand, with strong scalability and flexible call methods. Many method calls take a variety of forms and support multiple ways of passing parameters. The following is a simple arrangement of the way of use

Construct Moment object

MomentJS encapsulates time as an object, a moment object, which can be constructed in a variety of ways, including passing in strings, arrays, and objects.

Current system time

If nothing is passed, get the current system time.

var now = moment()
Copy the code

String construction

You can pass in a string, which is first checked to see if the format of the string conforms to the ISO 8601 format, and if not, new Date(string) is called to construct it.

Known format string

moment('2017-01-02'); // moment('the 2017-01-02 13'); // moment('the 2017-01-02 12'); // year month day hour minute moment'the 2017-01-02 13:12:52'); // year month day hour minute second moment('the 2017-01-02 13:12:52. 123'); // year month day hour minute second millisecondCopy the code

String + format

If the date format does not conform to the ISO 8601 format, but you know the format of the input string, you can also parse it in this way. The syntax for parsing is as follows:

moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);
Copy the code

The first is a format that is given at a time and is passed in as a second argument

moment('the 12-25-1995 12/43/53'.'MM-DD-YYYY HH/mm/ss')
Copy the code

The following table describes the meanings of format letters

Input Example Description
YYYY 2014 Four-digit year
YY 14 Two-digit year
Q 1.. 4 Quarter, set the month to the first month of the quarter
M MM 1.. 12 in
MMM MMMM Jan.. December In the name of the
D DD 1.. 31 The day of the month
DDD DDDD 1.. 365 The day of the year
H HH 0.. 23 24-hour
h hh 1.. 12 12 hours system
m mm 0.. 59 minutes
s ss 0.. 59 seconds

Second, you can pass in the local region key as a third parameter.

moment('2012 juillet'.'YYYY MMM'.'fr');
moment('2012 July'.'YYYY MMM'.'en');
Copy the code

MomentJS ‘matching pattern is very loose and can lead to unwanted behavior. As of version 2.3.0, we can pass a Boolean at the end to make Moment use strict pattern matching. Strict mode requires that the input string and format be exactly the same.

moment('It is 2012-05-25'.'YYYY-MM-DD').isValid();       // true
moment('It is 2012-05-25'.'YYYY-MM-DD'.true).isValid(); // false
moment('2012-05-25'.'YYYY-MM-DD'.true).isValid(); // true
Copy the code

String + multiple formats

If you don’t know exactly what format the input string is in, but you know it is in one of several formats, you can pass in multiple formats as an array, and the output will be whichever format is matched first.

moment("12-25-1995"["MM-DD-YYYY"."YYYY-MM-DD"]);
Copy the code

object

We can also create a moment object by passing in an object that contains properties of time units.

moment({ y    :2010, M     :3, d   :5, h    :15, m      :10, s      :3, ms          :123});
moment({ year :2010, month :3, day :5, hour :15, minute :10, second :3, millisecond :123});
moment({ years:2010, months:3, days:5, hours:15, minutes:10, seconds:3, milliseconds:123});
moment({ years:2010, months:3, date:5, hours:15, minutes:10, seconds:3, milliseconds:123});
Copy the code

Both day and date in the code above represent the day of the current month.

The Date object

We can also create a moment object by passing in a JS native Date object.

var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
Copy the code

An array of

We can create a moment object by passing in an array of numbers, each of which means something like this:

/ / (year, month, day,, points, seconds, milliseconds] my moment ([2010, 1, 14, 15, 25, 50, 125]). // February 14, 2010 15:25min 50sec 125msCopy the code

Note that months, hours, minutes, seconds, and milliseconds in the array all start at 0, while years and days all start at 1.

The value and is assigned

MomentJS uses reloadable GET and set methods, very similar to our previous form in jQuery. We can call these methods to get without passing an argument and to set with passing an argument.

Built-in function

Gets or sets milliseconds, ranging from 0 to 999

moment().millisecond(Number);
moment().millisecond(); // Number
moment().milliseconds(Number);
moment().milliseconds(); // Number
Copy the code

Gets or sets seconds, ranging from 0 to 59

moment().second(Number);
moment().second(); // Number
moment().seconds(Number);
moment().seconds(); // Number
Copy the code

Gets or sets the minutes, ranging from 0 to 59

moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
Copy the code

Gets or sets the hour, ranging from 0 to 23

moment().hour(Number);
moment().hour(); // Number
moment().hours(Number);
moment().hours(); // Number
Copy the code

Gets or sets the date, ranging from 1 to 31

moment().date(Number);
moment().date(); // Number
moment().dates(Number);
moment().dates(); // Number
Copy the code

Gets or sets the day of the week, ranging from 0 (Sunday) to 6 (Saturday)

moment().day(Number|String);
moment().day(); // Number
moment().days(Number|String);
moment().days(); // Number
Copy the code

Gets or sets the number of days in a year, ranging from 1 to 366

moment().dayOfYear(Number);
moment().dayOfYear(); // Number
Copy the code

Gets or sets the week of the year

moment().week(Number);
moment().week(); // Number
moment().weeks(Number);
moment().weeks(); // Number
Copy the code

Gets or sets the month of the year, ranging from 0 to 11

moment().month(Number|String);
moment().month(); // Number
moment().months(Number|String);
moment().months(); // Number
Copy the code

Gets or sets the quarter, ranging from 1 to 4

moment().quarter(); // Number
moment().quarter(Number);
Copy the code

Gets or sets the year, ranging from -270,000 to 270,000

moment().year(Number);
moment().year(); // Number
moment().years(Number);
moment().years(); // Number
Copy the code

The value and assignment function

In addition to the many functions mentioned above, MomentJS also has a function for unifying values and assignments, get and set.

moment().get('year');
moment().get('month');  // 0 to 11
moment().get('date');
moment().get('hour');
moment().get('minute');
moment().get('second');
moment().get('millisecond');
Copy the code

The set function takes the unit as the first argument and the value of the unit as the second argument. If you want to set multiple values, you can also pass in an object.

moment().set('year', 2013);
moment().set('month', 3); My moment / / April (.) set ('date', 1);
moment().set('hour', 13);
moment().set('minute', 20);
moment().set('second', 30);
moment().set('millisecond', 123);

moment().set({'year': 2013, 'month': 3});
Copy the code

Max/min function

The Max function can return the largest instance of a given moment object, which is the one closest to the future.

var a = moment('2017-12-01');
var b = moment('2017-12-06');
moment.max(a, b);  // b
Copy the code

The min function can return the smallest instance of a given moment object, that is, the one closest to the past.

var a = moment('2017-12-01');
var b = moment('2017-12-06');
moment.min(a, b);  // a
Copy the code

operation

Sometimes, we need to perform a series of operations on time, the most common of which is addition and subtraction. MomentJS provides a lot of ways for us to call it. MomentJS uses a similar pattern to jQuery, using chained calls to functions that allow us to chain operations, as shown below:

moment()
  .add(7, 'days')
  .subtract(1, 'months')
  .year(2009)
  .hours(0)
  .minutes(0)
  .seconds(0);
Copy the code

The add additive

The add function allows us to rewind the Moment object, which has the following syntax:

moment().add(Number, String);
moment().add(Duration);
moment().add(Object);
Copy the code

We can pass in the desired amount and unit of time, for example, 7 days later:

moment().add(7, 'days');
Copy the code

Of course, the add function also allows us to provide abbreviations for time units:

moment().add(7, 'd');
Copy the code
Unit of time abbreviations
years y
quarters Q
months M
weeks W
days d
hours h
minutes m
seconds s
milliseconds ms

If you want to add different time units at the same time, you can pass it as an object:

moment().add(7, 'days').add(1, 'months');
moment().add({days:7,months:1});
Copy the code

Note that if the number of days of the original date exceeds the total number of days in the month of the newly added date, it becomes the last day of the month:

// 01-31
moment([2010, 0, 31]);                  

// 02-28 
moment([2010, 0, 31]).add(1, 'months'); // There is no 31st day in February, so it automatically becomes the last day, i.e. 28thCopy the code

Subtract subtraction

Subtract is used similarly to add except that the time is pushed forward.

moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);
Copy the code

StartOf Start time

The startOf function sets the time of the Moment object to the start time of the incoming unit.

Moment () // Current time 2017-12-09 moment().startof ('year'); // Early 2017-01-01 moment().startof ('month'); // 2017-12-01 moment().startof ()'quarter'); 2017-10-01 moment().startof ()'week'); Moment ().startof ()'isoWeek'); Moment ().startof () moment().startof ('day'); Moment ().startof ()'hour'); 2017-12-09 13:00:00:000 moment().startof ()'minute'); 2017-12-09 13:14:00:000 moment().startof ('second'); // The current second starts todayCopy the code

EndOf Indicates the end time

The endOf function sets the Moment object’s time to the end time of the incoming unit. The usage is similar to startOf.

moment().endOf(String);
Copy the code

According to

Once we have parsed and manipulated the Moment object, we need to present the final result.

The format to format

The format function takes the token string and replaces the token with the corresponding value.

moment().format();                                // "2014-09-08T08:02:17-05:00" (ISO 8601)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA");                       // "Sun, 3PM"
Copy the code

The corresponding relationship is shown in the following table:

Token The input
month M 1, 2.. 11 to 12
Mo 1st 2nd … 11th 12th
MM 01, 02… 11 to 12
MMM Jan Feb … Nov Dec
MMMM January February … November December
quarter Q 1 2 3 4
Day of the month D 1, 2… 30 and 31
Do 1st 2nd … 30th 31st
DD 01, 02… 30 and 31
Days of a year DDD 1, 2… 365, 366,
DDDo st 2nd … 365th 366th
DDDD 001 002… 365, 366,
Midweek d 0 1… 5 and 6
do 0th 1st … 5th 6th
dd Su Mo … Fr Sa
ddd Sun Mon … Fri Sat
dddd Sunday Monday … Friday Saturday
Midyear week w 1, 2… 52 and 53
wo 1st 2nd … 52nd 53rd
ww 01, 02… 52 and 53
years YY 70 71… 29 and 30
YYYY 1970 1971… 2029, 2030,
AM/PM A AM PM
a am pm
hours H 0 1 … 22 23
HH 00 01 … 22 23
h 1, 2… 11 to 12
hh 01, 02… 11 to 12
minutes m 0 1… 58 59
mm 00 01… 58 59
seconds s 0 1… 58 59
ss 00 01… 58 59
ms ms 000 001… 998, 999,

The diff jet lag

grammar

moment().diff(Moment|String|Number|Date|Array);
moment().diff(Moment|String|Number|Date|Array, String);
moment().diff(Moment|String|Number|Date|Array, String, Boolean);
Copy the code

The diff function retrieves the time difference between two Moment objects. The default is milliseconds.

var a = moment([2017, 12, 29]);
var b = moment([2017, 12, 28]);
a.diff(b) // 86400000
Copy the code

In addition to getting milliseconds, the diff function can also get additional units of time, passed in as a second argument:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days'/ / 1Copy the code

The measurement units are years, months, weeks, days, hours, minutes, seconds, and milliseconds. By default, the value returned is dropped down, with decimals removed. If you want to be precise and get a decimal value, pass true as the third argument.

var a = moment([2008, 6]);
var b = moment([2007, 0]);
a.diff(b, 'years');       // 1
a.diff(b, 'years'.true); / / 1.5Copy the code

DaysInMonth Obtains the number of days in the current month

DaysInMonth Obtains the total number of days in the current month

moment("2012-02"."YYYY-MM").daysInMonth() // 29
moment("2012-01"."YYYY-MM").daysInMonth() // 31
Copy the code

ToDate converts to a Date object

Convert the Moment object to a JS native Date object

ToArray converts to an array

Returns an array of times, representing the same meaning as the array passed in when constructing the Moment object.

moment().toArray(); // [2017, 12, 9, 13, 40, 16, 154];
Copy the code

toObject

Turn the Moment object into an object containing year, month, day, hour, minute, second, millisecond.

moment().toObject()  // {
                     //     years: 2017
                     //     months: 12
                     //     date: 9,
                     //     hours: 13,
                     //     minutes: 40,
                     //     seconds: 18,
                     //     milliseconds: 600
                     // }
Copy the code

The query

The query operation is mainly used to determine whether a Moment meets certain conditions.

isBefore

moment().isBefore(Moment|String|Number|Date|Array);
moment().isBefore(Moment|String|Number|Date|Array, String);
Copy the code

IsBefore determines whether a moment object isBefore a certain point in time.

moment('2010-10-20').isBefore('2010-10-21'); // true
Copy the code

The default unit of comparison is milliseconds, but if we want to limit it to another unit of time, we can pass it in as a second argument. The units accepted are the same as those supported by startOf.

console.log(moment('2017-11-03').isBefore('2017-11-06'))
console.log(moment('2017-11-03').isBefore('2017-11-06'.'year'))
console.log(moment('2017-11-03').isBefore('2018-11-06'.'year'))
Copy the code

IsSame is the same

moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);
Copy the code

IsSame Determines whether a moment object is the same as another moment object.

moment('2010-10-20').isSame('2010-10-20'); // true
moment('2010-10-20').isSame('2010-10-21'); // false
Copy the code

Similarly, if we want to change the comparison to something else, we can pass it in as a second argument. The units accepted are the same as those supported by startOf.

moment('2010-10-20').isSame('2009-12-31'.'year');  // false
moment('2010-10-20').isSame('2010-01-01'.'year');  // true
Copy the code

When the second argument is passed, it matches all units of the same or greater value. For example, if a month is passed in, year and month will be compared, and if a date is passed in, year, month and day will be compared

// false, different year moment('2010-01-01').isSame('2011-01-01'.'month');

// false, different month moment('2010-01-01').isSame('2010-02-01'.'day');
Copy the code

IsAfter Whether after

IsBefore determines whether a moment object is after a certain point in time. The units accepted are the same as those supported by startOf.

moment('2010-10-20').isAfter('2010-10-19'); // true
Copy the code

IsBetween whether it isBetween

moment().isBetween(moment-like, moment-like); moment().isBetween(moment-like, moment-like, String); / / moment - like said my moment | String | Number | Date | ArrayCopy the code

Determine whether a moment object is between two other points in time.

moment('2017-10-20').isBetween('2017-10-19'.'2017-10-25'); // true
Copy the code

Pass the second parameter as the unit of the restriction. The units accepted are the same as those supported by startOf.

moment('2010-10-20').isBetween('2010-01-01'.'2012-01-01'.'year'); // false
moment('2010-10-20').isBetween('2009-12-31'.'2012-01-01'.'year'); // true
Copy the code

IsLeapYear Specifies whether it is a leap year

Return true for leap year, false for non-leap year.

moment([2000]).isLeapYear() // true
moment([2001]).isLeapYear() // false
moment([2100]).isLeapYear() // false
Copy the code

IsMoment Indicates whether a Moment object

Determine whether a Moment object is present

moment.isMoment() // false
moment.isMoment(new Date()) // false
moment.isMoment(moment()) // true
Copy the code

IsDate Specifies whether to Date the object

Determines whether a Date object is available

moment.isDate(); // false
moment.isDate(new Date()); // true
moment.isDate(moment()); // false
Copy the code

If you think it’s good, check out my Nuggets page. Please visit my blog for more articles