Moment.js Common usage

Source: Internet
Author: User
Tags add time diff iso 8601

Moment ("12-25-1995", "mm-dd-yyyy"); Returns a Moment object, a second string format

Common usage
Moment ("3-2014", "q-yyyy"); Q refers to a quarter
Moment ("3-2014", "X"); Lowercase x is millisecond, uppercase X is second level
Moment ("125-2014", "ddd-yyyy"); DDD is the first day of the year


If the time is set to an illegal time, the IsValid () method is used to verify that it will return false

Moment (' one to One '). IsValid (); False

You can create a moment using an object that represents a time unit, as follows:
Moment ({years:2010, months:3, Date:5, hours:15, Minutes:10, Seconds:3, milliseconds:123});
Moment ({y:2010, M:3, D:5, h:15, M:10, S:3, ms:123});//abbreviation


Initialize using UNIX offset (milliseconds)
Moment (Number) Example: Moment (1567851564654)

class using the Unix timestamp (seconds)
Moment.unix (number) Example: Moment.unix (86453456445654)

Moment object Replication
Implicitly calling the moment () method for replication
var a = Moment ([2012]);
var B = Moment (a);

Show replication using the Moment.clone () method
var a = Moment ([2012]);
var B = A.clone ();

------------------------------------------------------

Get/set

Moment.js uses overloaded getters and setters, which you may have seen in jquery. Calling these methods when you do not specify parameters is a getter,
Calling these methods when specifying parameters is a setters

Moment (). seconds (+) = = = New Date (). setseconds (30);
Moment (). seconds () = = = New Date (). getseconds ();
Mapping relationships under UTC
MOMENT.UTC (). seconds (+) = = = New Date (). setUTCSeconds (30);
MOMENT.UTC (). seconds () = = = New Date (). getUTCSeconds ();

The setting of the second is the same as the value, other similar:
Moment (). second (number);
Moment (). second (); Number
The valid input value is 0?59, which will affect the corresponding score after it is exceeded.

Take value (Get)
Moment (). Get (' year ');
Moment (). Get (' month '); 0 to 11
Moment (). Get (' date ');
Moment (). Get (' millisecond '); 0 to 999
Assignment (Set)
Moment (). Set (String, Int);
Moment (). Set (Object (String, Int));
Moment (). Set (' Year ', 2013);
Moment (). Set (' Month ', 3); April
Moment (). Set (' Date ', 1);
Moment (). Set (' Millisecond ', 123);

Moment (). Set ({' Year ': $, ' Month ': 3});

Moment.max (Moment[,moment ...]) returns the maximum value, with the same minimum value moment.min (moment[,moment ...])

var a = Moment (). Subtract (1, ' Day ');
var B = Moment (). Add (1, ' Day ');
Moment.max (A, b); B


------------------------------------------------

Operations such as date-time plus and minus

The moment uses a continuous interface pattern, also called a method chain. This allows you to make method calls like this:
Moment (). Add (7, ' days '). Subtract (1, ' months '). Year (a). Hours (0). Minutes (0). seconds (0);

Addition (ADD)
Moment (). Add (number, String), Example: Moment (). Add (7, ' days '); The following description unit can be abbreviated

When you add more than one time unit to a time, you can either pass the method chain or implement it through an object:
Moment (). Add (7, ' days '). Add (1, ' months '); Method Chain Implementation
Moment (). Add ({days:7,months:1}); Object literal implementation


Subtraction (Subtract)
Moment (). Subtract (number, String); Example: Moment (). Subtract (7, ' days '); The following description unit can be abbreviated

Start time (start of the time) is set to the original moment unit for a certain time.
Moment (). StartOf (String);

Moment (). StartOf (' year '); Set to the first day of January this year
Moment (). StartOf (' month '); Set to the first day of the month
Moment (). StartOf (' quarter '); Set to the first day of the first month of the quarter
Moment (). StartOf (' Week '); Set to the first day of the week
Moment (). StartOf (' Isoweek '); Set to ISO on the first day of the week
Moment (). StartOf (' Day '); Set to today's 12:00

End time (end of time) similar to start
Moment (). EndOf (String);

Moment (). EndOf ("year"); Set to this year's 12-31 11:59:59.999 pm


Localization (local)

Moment (). local (), set a flag on the original moment time, and use date#get* and date#set* internally instead of date#getutc* and date#setutc*

var a = MOMENT.UTC ([2011, 0, 1, 8]);
A.hours (); 8 UTC
A.local ();
A.hours (); 0 PST

UTC is the opposite of localization
Moment (). UTC ();
Set a flag for the original moment time, using date#getutc* and date#setutc* instead of date#get* and date#set* for its internal use


UTC offset (UTC)
Moment (). Utcoffset (); Sets or gets a UTC offset that is divided into units. Attention is divided into units
Moment (). Utcoffset (number| String);

Gets the UTC offset of the current object:
Moment (). Utcoffset (); ( -240, -120, -60, 0, all, +, etc.)

When the input is less than 16 and less than 16, moment will understand that the input is the hour

Moment (). Utcoffset (8); Set the hour offset
Moment (). Utcoffset (480); Set the minute offset (8 * 60)

Time zone offset (Timezone offset), which should be the opposite of the UTC offset, (UTC offset is relative to UTC time, time zone offset refers to local)

Sets or gets a time zone offset in minutes. Attention is divided into units
Moment (). zone ();
Moment (). Zone (number| String);


-----------------------------------------------------------

Date-time formatting

Formatting (format)
Moment (). Format ();
Moment (). Format (String);
Cases:
Moment (). Format (); "2014-09-08t08:02:17-05:00" (ISO 8601)
Moment (). Format ("dddd, MMMM do YYYY, h:mm:ss a"); "Sunday, February 14th, 3:25:50 PM"
Moment (). Format ("X"); 1360013296123
Moment (). Format (' YYYY MM DD '); "Invalid Date"


Slack (before, relative to the current time)
Moment ([0, +]). Fromnow (); 10 years ago
If set to true, a value with no suffix is obtained:
Moment ([0, +]). Fromnow (); 10 years ago
Moment ([0, +]). Fromnow (True); 10

Time difference (before)
If you want to show a moment time with another relationship, you can use the moment (). From () method:
var a = Moment ([2007, 0, 28]);
var B = Moment ([2007, 0, 29]);
A.from (b)//"A day Ago"-1 days ago


As with moment (). from (), you can also set the second argument to true, and then get a value that does not contain a suffix. This is useful when displaying a time difference of two times:
var start = Moment ([2007, 0, 5]);
var end = Moment ([2007, 0, 10]);
End.from (start); "In 5 days"
End.from (start, true); "5 Days"

Time difference (after) moment ("). Tonow () and Moment ("). Fromnow opposite


Time difference (milliseconds) gets a millisecond of time difference, Moment (). The diff () method is similar to the moment (). from () method.
Moment (). diff (Moment| String| number| date| Array);

var a = Moment ([2007, 0, 29]);
var B = Moment ([2007, 0, 28]);
A.diff (b)//86400000

Unix offset (ms) Moment (). ValueOf () will simply output a millisecond-level Unix time offset, similar to date.valueof ().

Moment (). ValueOf ();
Moment (). ValueOf (); 1318874398806

Unix timestamp (seconds) moment (). UNIX () returns a UNIX timestamp
Moment (). UNIX ();
Moment (1318874398806). UNIX (); 1318874398 Note Unit is seconds

Date Reload: Days, date objects, arrays, objects
Days (month)
Moment (). DaysInMonth (); Gets the number of days in the current month.

Moment ("2012-02", "yyyy-mm"). DaysInMonth ()//29
Moment ("2012-01", "yyyy-mm"). DaysInMonth ()//31


JavaScript Date Object
Moment (). ToDate (); Gets a JavaScript date object through Moment.js, using the Moment (). ToDate () method
The date that will be returned is the object that moment is using, so any modification to date will also cause moment to change. If you only want to get a date copy,
You should use the moment (). Clone () method before calling the moment (). ToDate () method.

Array
Moment (). ToArray (); Returns an array that returns the mirror value of the new Date () parameter.
Moment (). ToArray (); [2013, 1, 4, 14, 40, 16, 154]; [year, month, day, time, minute, second, millisecond]

Object
Moment (). Toobject (); Returns an object that includes: year, month, day, time, minute, second, millisecond
Moment (). Toobject ()//{
years:2015
Months:6
Date:26,
Hours:1,
Minutes:53,
Seconds:14,
milliseconds:600
// }

----------------------------------------------------------------

Date-time Query

1. Whether before: Isbefore ()
Moment (). Isbefore (moment| String| number| date| Array); Check if the moment is before another time.
Example: Moment (' 2010-10-20 '). Isbefore (' 2010-10-21 '); True

If you want to limit the comparison granularity to units other than milliseconds, you can set the units to compare in the second parameter.
When the second parameter is set, not only the units of this level are compared, but the year, month, and day are compared when the units are compared in days.
Moment (' 2010-10-20 '). Isbefore (' 2010-12-31 ', ' Year '); False
Moment (' 2010-10-20 '). Isbefore (' 2011-01-01 ', ' Year '); True

Support for year month Week day hour minute second, milliseconds not supported

2. Whether the same: Issame () sometimes very useful

Moment (). Issame (moment| String| number| date| Array); Check if the moment is the same as another time.
Example: Moment (' 2010-10-20 '). Issame (' 2010-10-20 '); True

If you want to limit the comparison granularity to units other than milliseconds, you can set the units to compare in the second parameter. Can be used to compare whether in the same year, the same one months, or the same day, etc.

Moment (' 2010-10-20 '). Issame (' 2009-12-31 ', ' Year '); False
Moment (' 2010-10-20 '). Issame (' 2010-01-01 ', ' Year '); True
Moment (' 2010-10-20 '). Issame (' 2010-12-31 ', ' Year '); True
Moment (' 2010-10-20 '). Issame (' 2011-01-01 ', ' Day '); False

When the second parameter is set, not only the units of this level are compared. When you enter low-level units, you also compare their parent units,
such as: when compared in days, the same time will compare the year, month, day.
Moment (' 2010-01-01 '). Issame (' 2011-01-01 ', ' month '); False, different year
Moment (' 2010-01-01 '). Issame (' 2010-02-01 ', ' Day '); False, Month different

3. After: Isafter () opposite Isbefore ()

4. Whether between: Isbetween ()

Moment (). Isbetween (Moment-like, moment-like); Check whether the moment is between the other two time, the optional comparison unit can be: minutes, hours, Tian Deng.
Check whether the moment is between the other two time, the optional comparison unit can be: minutes, hours, Tian Deng.
Moment (' 2010-10-20 '). Isbetween (' 2010-10-19 ', ' 2010-10-25 '); True

If you want to limit the comparison granularity to units other than milliseconds, you can set the units to compare in the third parameter.
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


5. Whether leap year: isleapyear () Moment (). Isleapyear () in a leap year is return true, otherwise false is returned.

6. Whether the moment object: the Ismoment () moment.ismoment () method is used to check if it is a moment object.

7. Whether the Date object: The IsDate () Moment.isdate () method is used to check if it is a JavaScript date object.


-----------------------------------------------------

Time period (durations)

1. Creation time period: Duration ()

Moment.duration (number, String);
Moment.duration (number);
Moment.duration (Object);
Moment.duration (String);


Creates a time period through the Moment.duration () method and passes in a millisecond-level timestamp.
Moment.duration (100); 100 ms

If you want to use non-millisecond units when creating a time period, you can pass in time units like this: you can use shorthand
Moment.duration (2, ' seconds ');
Moment.duration (2, ' minutes ');
Moment.duration (2, ' hours ');

Like Moment#add, you can pass in an object that contains multiple units as needed.
Moment.duration ({
Seconds:2,
Minutes:2,
Hours:2,
Days:2,
Weeks:2,
Months:2,
Years:2
});

Finally, you can pass in a string creation time period

Moment.duration (' 23:59:59 '); The second part also supports this 23:59:59.999


2. Add Time: Add () adds time to the original time period.
Moment.duration (). Add (number, String);
Moment.duration (). Add (number);
Moment.duration (). Add (duration);
Moment.duration (). Add (Object);
The shorthand unit of time used when creating a time period is also applicable here. You can pass in the second argument.
var a = moment.duration (1, ' d ');
var B = moment.duration (2, ' d ');
A.add (b). days (); 3

3. Whether time period: isduration ()
Moment.isduration (obj); Check if it is a valid time period object, using Moment.isduration ()

Moment.isduration ()//False
Moment.isduration (New Date ())//False
Moment.isduration (Moment ())//False
Moment.isduration (Moment.duration ())//True
Moment.isduration (Moment.duration (2, ' minutes '))//True

Moment.js Common usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.