#Where to use it
Moment was designed to work both in the browser and in Node.JS.
All code will work in both environments. All unit tests are run in both environments.
Moment was designed to work both in the browser and in Node.JS.
All code will work in both environments. All unit tests are run in both environments.
npm install moment
var moment = require('moment');
moment().format();
<script src="moment.js"></script>
<script>
moment().format();
</script>
require.config({
paths: {
"moment": "path/to/moment",
}
});
define(["moment"], function (moment) {
moment().format();
});
Instead of modifying the native Date.prototype, Moment.js creates a wrapper for the Date object. To get this wrapper object, simply call moment() with one of the supported input types.
The Moment prototype is exposed through moment.fn. If you want to add your own functions, that is where you would put them.
For ease of reference, any method on the Moment.prototype will be referenced in the docs as moment#method. So Moment.prototype.format == moment.fn.format == moment#format.
moment();
To get the current date and time, just call moment() with no parameters.
var now = moment();
This is essentially the same as calling moment(new Date()).
moment(String);
You can create a moment from a string that can be parsed by Date.parse.
var day = moment("Dec 25, 1995");
Warning Browser support for this is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For more consistent results, you should use String + Format.
There is one exception. Moment.js does detect if you are using an ISO-8601 string and will parse that correctly without a format string.
The following ISO-8601 formats are supported across all browsers.
"YYYY-MM-DD"
"YYYY-MM-DDTHH"
"YYYY-MM-DD HH"
"YYYY-MM-DDTHH:mm"
"YYYY-MM-DD HH:mm"
"YYYY-MM-DDTHH:mm:ss"
"YYYY-MM-DD HH:mm:ss"
"YYYY-MM-DDTHH:mm:ss.SSS"
"YYYY-MM-DD HH:mm:ss.SSS"
"YYYY-MM-DDTHH:mm:ss Z"
"YYYY-MM-DD HH:mm:ss Z"
Note: Automatic cross browser ISO-8601 support was added in version 1.5.0
If a string does not match any of the above formats and is not able to be parsed with Date.parse, moment#isValid will return false.
moment("not a real date").isValid(); // false
moment(String, String);
moment(String, String, String);
If you know the format of an input string, you can use that to parse a moment.
moment("12-25-1995", "MM-DD-YYYY");
The parser ignores non-alphanumeric characters, so both of the following will return the same thing.
moment("12-25-1995", "MM-DD-YYYY");
moment("12\25\1995", "MM-DD-YYYY");
The parsing tokens are similar to the formatting tokens used in moment#format.
| Input | Output |
|---|---|
| M, MM | Month Number (1 - 12) |
| MMM, MMMM | Month Name (In currently language set by `moment.lang()`) |
| D, DD | Day of month |
| DDD, DDDD | Day of year |
| d, dd, ddd, dddd | Day of week (NOTE: the input for these tokens is ignored, as there are 4-5 weeks in a month, and it would be impossible to get the day of the month based off the day of the week) |
| YY | 2 digit year (if greater than 68 will return 1900's, otherwise 2000's) |
| YYYY | 4 digit year |
| a, A | AM/PM |
| H, HH | 24 hour time |
| h, hh | 12 hour time (use in conjunction with a or A) |
| m, mm | Minutes |
| s, ss | Seconds |
| S | Deciseconds (1/10th of a second) |
| SS | Centiseconds (1/100th of a second) |
| SSS | Milliseconds (1/1000th of a second) |
| Z, ZZ | Timezone offset as `+0700` or `+07:30` |
| X | Unix timestamp |
Z ZZ were added in 1.2.0. S SS SSS were added in 1.6.0. X was added in 2.0.0.
Unless you specify a timezone offset, parsing a string will create a date in the current timezone.
moment("2010-10-20 4:30", "YYYY-MM-DD HH:mm"); // parsed as 4:30 local time
moment("2010-10-20 4:30 +0000", "YYYY-MM-DD HH:mm Z"); // parsed as 4:30 GMT
If the moment that results from the parsed input does not exist, moment#isValid will return false.
moment("2010 13", "YYYY MM").isValid(); // false (not a real month)
moment("2010 11 31", "YYYY MM DD").isValid(); // false (not a real day)
moment("2010 2 29", "YYYY MM DD").isValid(); // false (not a leap year)
moment("2010 notamonth 29", "YYYY MMM DD").isValid(); // false (not a real month name)
As of version 2.0.0, a language key can be passed as the third parameter to moment() and moment.utc().
moment('2012 juillet', 'YYYY MMM', 'fr');
moment('2012 July', 'YYYY MMM', 'en');
moment(String, String[]);
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
moment("12-25-1995", ["MM-DD-YYYY", "YYYY-MM-DD"]);
This approach is fundamentally problematic in cases like the following, where there is a difference in big, medium, or little endian date formats.
moment("05-06-1995", ["MM-DD-YYYY", "DD-MM-YYYY"]); // June 5th or May 6th?
moment("040506", ["MMDDYY", "DDMMYY", "YYMMDD"]); // Apr 5 2006, May 4 2006, or May 6 2004?
This is also the reason Moment.js does not do "magical" string parsing.
Note: Parsing multiple formats is considerably slower than parsing a single format. If you can avoid it, it is much faster to parse a single format.
moment(Number);
Similar to new Date(Number), you can create a moment by passing an integer value representing the number of milliseconds since the Unix Epoch (Jan 1 1970 12AM UTC).
var day = moment(1318781876406);
moment.unix(Number)
To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).
var day = moment.unix(1318781876);
This is implemented as moment(timestamp * 1000), so partial seconds in the input timestamp are included.
var day = moment.unix(1318781876.721);
moment(Date);
You can create a Moment with a pre-existing native Javascript Date object.
var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);
This is the fastest way to get a Moment.js wrapper.
moment(Number[]);
You can create a moment with an array of numbers that mirror the parameters passed to new Date()
[year, month, day, hour, minute, second, millisecond]
moment([2010, 1, 14, 15, 25, 50, 125]); // February 14th, 3:25:50.125 PM
Any value past the year is optional, and will default to the lowest possible number.
moment([2010]); // January 1st
moment([2010, 6]); // July 1st
moment([2010, 6, 10]); // July 10th
Construction with an array will create a date in the current timezone. To create a date from an array at UTC, use moment.utc(Number[]).
moment.utc([2010, 1, 14, 15, 25, 50, 125]);
Note: Because this mirrors the native Date parameters, the following parameters are all zero indexed: months, hours, minutes, seconds, and milliseconds. Years and days of the month are 1 indexed.
This is often the cause of frustration, especially with months, so take note!
If the date represented by the array does not exist, moment#isValid will return false.
moment([2010, 13]).isValid(); // false (not a real month)
moment([2010, 11, 31]).isValid(); // false (not a real day)
moment([2010, 2, 29]).isValid(); // false (not a leap year)
moment(String);
ASP.NET returns dates in JSON as /Date(1198908717056)/ or /Date(1198908717056-0700)/
If a string that matches this format is passed in, it will be parsed correctly.
moment("/Date(1198908717056-0700)/"); // December 28 2007 10:11 PM
moment(Moment);
All moments are mutable. If you want a clone of a moment, you can do so explicitly or implicitly.
Calling moment() on a moment will clone it.
var a = moment([2012]);
var b = moment(a);
a.year(2000);
b.year(); // 2012
Additionally, you can call moment#clone to clone a moment.
var a = moment([2012]);
var b = a.clone();
a.year(2000);
b.year(); // 2012
moment.utc();
moment.utc(Number);
moment.utc(Number[]);
moment.utc(String);
moment.utc(String, String);
moment.utc(String, String[]);
moment.utc(String, String, String);
moment.utc(Moment);
moment.utc(Date);
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
This brings us to an interesting feature of Moment.js. UTC mode.
While in UTC mode, all display methods will display in UTC time instead of local time.
moment().format(); // 2013-02-04T10:35:24-08:00
moment.utc().format(); // 2013-02-04T18:35:24+00:00
Additionally, while in UTC mode, all getters and setters will internally use the Date#getUTC* and Date#setUTC* methods instead of the Date#get* and Date#set* methods.
moment.utc().seconds(30) === new Date().setUTCSeconds(30);
moment.utc().seconds() === new Date().getUTCSeconds();
It is important to note that though the displays differ above, they are both the same moment in time.
var a = moment();
var b = moment.utc();
a.format(); // 2013-02-04T10:35:24-08:00
b.format(); // 2013-02-04T18:35:24+00:00
a.valueOf(); // 1360002924000
b.valueOf(); // 1360002924000
Any moment created with moment.utc() will be in UTC mode, and any moment created with moment() will not.
To switch from UTC to local time, you can use moment#utc or moment#local.
var a = moment.utc([2011, 0, 1, 8]);
a.hours(); // 8 UTC
a.local();
a.hours(); // 0 PST
moment().isValid();
The main moment() function is very flexible and will allow overflowing in parsing input. For example, moment("2012-01-40", "YYYY-MM-DD") will overflow the date value into the months, making the actual moment Feb 9 (31 days in Jan + 9 days into Feb).
This can be useful when getting things like the 150th day of the year, or the 500th minute in a day, however, it can be problematic when trying to parse user input.
moment#isValid was added to check if the input for a moment is indeed a valid date.
Note: It is not intended to be used to validate that the input string matches the format string. Because the strictness of format matching can vary depending on the application and business requirements, this sort of validation is not included in Moment.js.
Instead, moment#isValid answers questions like "Does March 32nd exist?" and "Does February 29th 2011 exist?".
moment("2011-10-10", "YYYY-MM-DD").isValid(); // true
moment("2011-10-50", "YYYY-MM-DD").isValid(); // false (bad day of month)
It works with ISO 8601 parsing.
moment("2011-10-10T10:20:90").isValid(); // false (bad seconds)
It works with an array of numbers that mirror the parameters passed to new Date().
moment([2011, 0, 1]).isValid(); // true
moment([2011, 0, 50]).isValid(); // false (bad day of month)
It also works with a string that gets passed to Date.parse()
moment("not a date").isValid(); // false
Note: The moment#isValid method will not work after manipulating the moment object with any of the manipulation methods.
moment("2011-10-10", "YYYY-MM-DD").isValid(); // true
moment("2011-10-10", "YYYY-MM-DD").date(20).isValid(); // false
Moment.js uses overloaded getters and setters. You may be familiar with this pattern from it's use in jQuery.
Calling these methods without parameters acts as a getter, and calling them with a parameter acts as a setter.
These map to the corresponding function on the native Date object.
moment().seconds(30) === new Date().setSeconds(30);
moment().seconds() === new Date().getSeconds();
If you are in UTC mode, they will map to the UTC equivalent.
moment.utc().seconds(30) === new Date().setUTCSeconds(30);
moment.utc().seconds() === new Date().getUTCSeconds();
For convenience, both singular and plural method names exist as of version 2.0.0.
Note: All of these methods mutate the original moment when used as setters.
moment().millisecond(Number);
moment().millisecond(); // Number
moment().milliseconds(Number);
moment().milliseconds(); // Number
Gets or sets the milliseconds.
Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds.
moment().second(Number);
moment().second(); // Number
moment().seconds(Number);
moment().seconds(); // Number
Gets or sets the seconds.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the minutes.
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
Gets or sets the minutes.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the hours.
moment().hour(Number);
moment().hour(); // Number
moment().hours(Number);
moment().hours(); // Number
Gets or sets the hour.
Accepts numbers from 0 to 23. If the range is exceeded, it will bubble up to the day.
moment().date(Number);
moment().date(); // Number
moment().dates(Number);
moment().dates(); // Number
Gets or sets the day of the month.
Accepts numbers from 1 to 31. If the range is exceeded, it will bubble up to the months.
Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.
moment().day(Number);
moment().day(); // Number
moment().days(Number);
moment().days(); // Number
Gets or sets the day of the week.
This method can be used to set the day of the week, with Sunday as 0 and Saturday as 6.
If the range is exceeded, it will bubble up to other weeks.
moment().day(-7); // last Sunday (0 - 7)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.
moment().dayOfYear(Number);
moment().dayOfYear(); // Number
Gets or sets the day of the year.
Accepts numbers from 1 to 366. If the range is exceeded, it will bubble up to the years.
moment().week(Number);
moment().week(); // Number
moment().weeks(Number);
moment().weeks(); // Number
Gets or sets the week of the year.
Because different locales define week of year numbering differently, Moment.js added moment#week to get/set the localized week of the year.
The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.
For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.
In France, Monday is the first day of the week, and the week with January 4th is the first week of the year.
The output of moment#week will depend on the locale/language for that moment.
When setting the week of the year, the day of the week is retained.
moment().isoWeek(Number);
moment().isoWeek(); // Number
moment().isoWeeks(Number);
moment().isoWeeks(); // Number
Gets or sets the ISO week of the year.
When setting the week of the year, the day of the week is retained.
moment().month(Number);
moment().month(); // Number
moment().months(Number);
moment().months(); // Number
Gets or sets the month.
Accepts numbers from 0 to 11. If the range is exceeded, it will bubble up to the year.
Note: Months are zero indexed, so January is month 0.
moment().year(Number);
moment().year(); // Number
moment().years(Number);
moment().years(); // Number
Gets or sets the year.
Accepts numbers from -270,000 to 270,000.
Once you have a Moment, you may want to manipulate it in some way. There are a number of methods to help with this.
Moment.js uses the fluent interface pattern, also known as method chaining. This allows you to do crazy things like the following.
moment().add('days', 7).subtract('months', 1).year(2009).hours(0).minutes(0).seconds(0);
Note: It should be noted that moments are mutable. Calling any of the manipulation methods will change the original moment.
If you want to create a copy and manipulate it, you should use moment#clone before manipulating the moment. More info on cloning.
moment().add(String, Number);
moment().add(Number, String); // 2.0.0
moment().add(Duration); // 1.6.0
moment().add(Object);
Mutates the original moment by adding time.
This is a pretty robust function for adding time to an existing moment. To add time, pass the key of what time you want to add, and the amount you want to add.
moment().add('days', 7);
There are some shorthand keys as well if you're into that whole brevity thing.
moment().add('d', 7);
| Key | Shorthand |
|---|---|
| years | y |
| months | M |
| weeks | w |
| days | d |
| hours | h |
| minutes | m |
| seconds | s |
| milliseconds | ms |
If you want to add multiple different keys at the same time, you can pass them in as an object literal.
moment().add('days', 7).add('months', 1); // with chaining
moment().add({days:7,months:1}); // with object literal
There are no upper limits for the amounts, so you can overload any of the parameters.
moment().add('milliseconds', 1000000); // a million milliseconds
moment().add('days', 360); // 360 days
If the day of the month on the original date is greater than the number of days in the final month,
the day of the month will change to the last day in the final month.
moment([2010, 0, 31]); // January 31
moment([2010, 0, 31]).add('months', 1); // February 28
There are also special considerations to keep in mind when adding time that crosses over Daylight Savings Time.
If you are adding years, months, weeks, or days, the original hour will always match the added hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US
m.hours(); // 5
m.add('days', 1).hours(); // 5
If you are adding hours, minutes, seconds, or milliseconds, the assumption is that you want precision to the hour, and will result in a different hour.
var m = moment(new Date(2011, 2, 12, 5, 0, 0)); // the day before DST in the US
m.hours(); // 5
m.add('hours', 24).hours(); // 6
Alternatively, you can use durations to add to moments.
var duration = moment.duration({'days' : 1});
moment([2012, 0, 31]).add(duration); // February 1
As of version 2.0.0, a reversed syntax is also supported to ease development. The syntaxes below will all work.
moment().add('seconds', 1);
moment().add('seconds', '1');
moment().add(1, 'seconds');
This syntax will not work. The first parameter would need to be a number, not a string.
moment().add('1', 'seconds');
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
Mutates the original moment by subtracting time.
This is exactly the same as moment#add, only instead of adding time, it subtracts time.
moment().subtract('days', 7);
moment().startOf(String);
Mutates the original moment by setting it to the start of a unit of time.
moment().startOf('year'); // set to January 1st, 12:00 am this year
moment().startOf('month'); // set to the first of this month, 12:00 am
moment().startOf('week'); // set to the first day of this week, 12:00 am
moment().startOf('day'); // set to 12:00 am today
moment().startOf('hour'); // set to now, but with 0 mins, 0 secs, and 0 ms
moment().startOf('minute'); // set to now, but with 0 seconds and 0 milliseconds
moment().startOf('second'); // same as moment().milliseconds(0);
These shortcuts are essentially the same as the following.
moment().startOf('year');
moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0);
moment().startOf('hour');
moment().minutes(0).seconds(0).milliseconds(0)
As of version 2.0.0, moment#startOf('day') replaced moment#sod.
moment().endOf(String);
Mutates the original moment by setting it to the end of a unit of time.
This is the same as moment#startOf, only instead of setting to the start of a unit of time, it sets to the end of a unit of time.
moment().endOf("year"); // set the moment to 12-31 11:59:59.999 pm this year
As of version 2.0.0, moment#endOf('day') replaced moment#eod.
moment().local();
Toggles a flag on the original moment to internally use Date#get* and Date#set* 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
See moment.utc() for more information on UTC mode.
moment().utc();
Toggles a flag on the original moment to internally use Date#getUTC* and Date#setUTC* instead of Date#get* and Date#set*.
var a = moment([2011, 0, 1, 8]);
a.hours(); // 8 PST
a.utc();
a.hours(); // 16 UTC
See moment.utc() for more information on UTC mode.
Once parsing and manipulation are done, you need some way to display the moment.
moment().format();
moment().format(String);
This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA"); // "Sun, 3PM"
There are a couple conventions used with the naming of the
| Token | Output | |
|---|---|---|
| Month | M | 1 2 ... 11 12 |
| Mo | 1st 2nd ... 11th 12th | |
| MM | 01 02 ... 11 12 | |
| MMM | Jan Feb ... Nov Dec | |
| MMMM | January February ... November December | |
| Day of Month | D | 1 2 ... 30 30 |
| Do | 1st 2nd ... 30th 31st | |
| DD | 01 02 ... 30 31 | |
| Day of Year | DDD | 1 2 ... 364 365 |
| DDDo | 1st 2nd ... 364th 365th | |
| DDDD | 001 002 ... 364 365 | |
| Day of Week | d | 0 1 ... 5 6 |
| do | 0th 1st ... 5th 6th | |
| ddd | Sun Mon ... Fri Sat | |
| dddd | Sunday Monday ... Friday Saturday | |
| Week of Year | w | 1 2 ... 52 53 |
| wo | 1st 2nd ... 52nd 53rd | |
| ww | 01 02 ... 52 53 | |
| ISO Week of Year | W | 1 2 ... 52 53 |
| Wo | 1st 2nd ... 52nd 53rd | |
| WW | 01 02 ... 52 53 | |
| Year | YY | 70 71 ... 29 30 |
| YYYY | 1970 1971 ... 2029 2030 | |
| AM/PM | A | AM PM |
| a | am pm | |
| Hour | H | 0 1 ... 22 23 |
| HH | 00 01 ... 22 23 | |
| h | 1 2 ... 11 12 | |
| hh | 01 02 ... 11 12 | |
| Minute | m | 0 1 ... 58 59 |
| mm | 00 01 ... 58 59 | |
| Second | s | 0 1 ... 58 59 |
| ss | 00 01 ... 58 59 | |
| Fractional Second | S | 0 1 ... 8 9 |
| SS | 0 1 ... 98 99 | |
| SSS | 0 1 ... 998 999 | |
| ss | 00 01 ... 58 59 | |
| Timezone | z or zz |
EST CST ... MST PST
Note: as of 1.6.0, the z/zz format tokens have been deprecated. Read more about it here. |
| Z | -07:00 -06:00 ... +06:00 +07:00 | |
| ZZ | -0700 -0600 ... +0600 +0700 | |
| Unix Timestamp | X | 1360013296 |
Z ZZ were added in 1.2.0. S SS SSS were added in 1.6.0. X was added in 2.0.0.
Because preferred formatting differs based on locale, there are a few tokens that can be used to format a moment based on its language.
There are upper and lower case variations on the same formats. The lowercase version is intended to be the shortened version of its uppercase counterpart.
| Time | LT | 8:30 PM |
| Month numeral, day of month, year | L | 09/04/1986 |
| l | 9/4/1986 | |
| Month name, day of month, year | LL | September 4th 1986 |
| ll | Sep 4 1986 | |
| Month name, day of month, year, time | LLL | September 4th 1986 8:30 PM |
| lll | Sep 4 1986 8:30 PM | |
| Month name, day of month, day of week, year, time | LLLL | Thursday, September 4th 1986 8:30 PM |
| llll | Thu, Sep 4 1986 8:30 PM |
L LL LLL LLLL LT are available in version 1.3.0. l ll lll llll are available in 2.0.0.
To escape characters in format strings, you can wrap the characters in square brackets.
moment().format('[today] DDDD'); // 'today Sunday'
Note: While these date formats are very similar to LDML date formats, there are a few minor differences regarding day of month, day of year, and day of week.
For a breakdown of a few different date formatting tokens across different languages, see this chart of date formatting tokens.
To compare Moment.js formatting speed against other libraries, check out this comparison against other libraries.
If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin. benjaminoakes/moment-strftime.
As of version 1.5.0, calling moment#format without a format will default to moment.defaultFormat. Out of the box, moment.defaultFormat is the ISO8601 format YYYY-MM-DDTHH:mm:ssZ.
moment().fromNow();
moment().fromNow(Boolean);
A common way of displaying time is handled by moment#fromNow. This is sometimes called timeago or relative time.
moment([2007, 0, 29]).fromNow(); // 4 years ago
If you pass true, you can get the value without the suffix.
moment([2007, 0, 29]).fromNow(); // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
The base strings are customized by the current language.
The breakdown of which string is displayed for each length of time is outlined in the table below.
| Range | Key | Sample Output |
|---|---|---|
| 0 to 45 seconds | s | seconds ago |
| 45 to 90 seconds | m | a minute ago |
| 90 seconds to 45 minutes | mm | 2 minutes ago ... 45 minutes ago |
| 45 to 90 minutes | h | an hour ago |
| 90 minutes to 22 hours | hh | 2 hours ago ... 22 hours ago |
| 22 to 36 hours | d | a day ago |
| 36 hours to 25 days | dd | 2 days ago ... 25 days ago |
| 25 to 45 days | M | a month ago |
| 45 to 345 days | MM | 2 months ago ... 11 months ago |
| 345 to 547 days (1.5 years) | y | a year ago |
| 548 days+ | yy | 2 years ago ... 20 years ago |
moment().from(Moment|String|Number|Date|Array);
moment().from(Moment|String|Number|Date|Array, Boolean);
You may want to display a moment in relation to a time other than now. In that case, you can use moment#from.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.from(b) // "a day ago"
The first parameter is anything you can pass to moment() or an actual Moment.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.from(b); // "a day ago"
a.from([2007, 0, 28]); // "a day ago"
a.from(new Date(2007, 0, 28)); // "a day ago"
a.from("1-28-2007"); // "a day ago"
Like moment#fromNow, passing true as the second parameter returns value without the suffix. This is useful wherever you need to have a human readable length of time.
var start = moment([2007, 0, 5]);
var end = moment([2007, 0, 10]);
start.from(end); // "in 5 days"
start.from(end, true); // "5 days"
moment().calendar();
Calendar time is displays time relative to now, but slightly differently than moment#fromNow.
moment#calendar will format a date with different strings depending on how close to today the date is.
| Last week | Last Monday 2:30 AM |
| The day before | Yesterday 2:30 AM |
| The same day | Today 2:30 AM |
| The next day | Tomorrow 2:30 AM |
| The next week | Sunday 2:30 AM |
| Everything else | 7/10/2011 |
These strings are localized, and can be customized.
moment().diff(Moment|String|Number|Date|Array);
moment().diff(Moment|String|Number|Date|Array, String);
moment().diff(Moment|String|Number|Date|Array, String, Boolean);
To get the difference in milliseconds, use moment#diff like you would use moment#from.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000
To get the difference in another unit of measurement, pass that measurement as the second argument.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
The supported measurements are years, months, weeks, days, hours, minutes, and seconds. For ease of development, the singular forms are supported as of 2.0.0. Units of measurement other than milliseconds are available in version 1.1.1.
By default, moment#diff will return number rounded down. If you want the floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned rounded number, not a rounded down number.
var a = moment([2007, 0]);
var b = moment([2008, 5]);
a.diff(b, 'years') // 1
a.diff(b, 'years', true) // 1.5
If the moment is later than the moment you are passing to moment.fn.diff, the return value will be negative.
var a = moment();
var b = moment().add('seconds', 1);
a.diff(b) // -1000
b.diff(a) // 1000
A easy way to think of this is by replacing .diff( with a minus operator.
// a < b
a.diff(b) // a - b < 0
b.diff(a) // b - a < 0
moment#diff has some special handling for month and year diffs. It is optimized to ensure that two months with the same date are always a whole number apart.
So Jan 15 to Feb 15 should be exactly 1 month.
Feb 28 to Mar 28 should be exactly 1 month.
Feb 28 2011 to Feb 28 2012 should be exactly 1 year.
See more discussion on the month and year diffs here
This change to month and year diffs was made in 2.0.0.
moment().valueOf();
+moment();
moment#valueOf simply outputs the number of milliseconds since the Unix Epoch, just like Date#valueOf.
moment(1318874398806).valueOf(); // 1318874398806
+moment(1318874398806); // 1318874398806
To get a Unix timestamp (the number of seconds since the epoch) from a Moment, use moment#unix.
moment().unix();
moment#unix outputs a Unix timestamp (the of seconds since the Unix Epoch).
moment(1318874398806).unix(); // 1318874398
This value is floored to the nearest second, and does not include a milliseconds component.
moment().zone();
Get the timezone offset in minutes.
moment().zone(); // (60, 120, 240, etc.)
moment().daysInMonth();
Get the number of days in the current month.
moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31
moment().toDate();
To get the native Date object that Moment.js wraps, use moment#toDate.
This will return the Date that the moment uses, so any changes to that Date will cause the moment to change. If you want a Date that is a copy, use moment#clone before you use moment#toDate.
moment#native has been replaced by moment#toDate and has been deprecated as of 1.6.0.
moment().toArray();
This returns an array that mirrors the parameters from new Date().
moment().toArray(); // [2013, 1, 4, 14, 40, 16, 154];
moment().toJSON();
When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string.
JSON.stringify({
postDate : moment()
}); // {"postDate":"2013-02-04T22:44:30.652Z"}
moment().isBefore(Moment|String|Number|Date|Array);
moment().isBefore(Moment|String|Number|Date|Array, String);
Check if a moment is before another moment.
moment('2010-10-20').isBefore('2010-10-21'); // true
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isBefore('2010-12-31', 'year'); // false
moment('2010-10-20').isBefore('2011-01-01', 'year'); // true
Like moment#isAfter and moment#isSame, any of the units of time that are supported for moment#startOf are supported for moment#isBefore. Year, month, week, day, hour, minute, and second.
moment().isSame(Moment|String|Number|Date|Array);
moment().isSame(Moment|String|Number|Date|Array, String);
Check if a moment is the same as another moment.
moment('2010-10-20').isSame('2010-10-20'); // true
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
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', 'year'); // false
Like moment#isAfter and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isSame. Year, month, week, day, hour, minute, and second.
moment().isAfter(Moment|String|Number|Date|Array);
moment().isAfter(Moment|String|Number|Date|Array, String);
Check if a moment is after another moment.
moment('2010-10-20').isAfter('2010-10-19'); // true
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
Like moment#isSame and moment#isBefore, any of the units of time that are supported for moment#startOf are supported for moment#isAfter. Year, month, week, day, hour, minute, and second.
moment().isLeapYear();
moment#isLeapYear returns true if that year is a leap year, and false if it is not.
moment([2000]).isLeapYear() // true
moment([2001]).isLeapYear() // false
moment([2100]).isLeapYear() // false
moment().isDST();
moment#isDST checks if the current moment is in daylight savings time.
moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST
moment.isMoment(obj);
To check if a variable is a moment object, use moment.isMoment().
moment.isMoment() // false
moment.isMoment(new Date()) // false
moment.isMoment(moment()) // true
Moment.js has pretty robust support for internationalization.
You can load multiple languages and easily switch between them.
In addition to assigning a global language, you can assign a language to a specific moment.
moment.lang(String);
moment.lang(String, Object);
By default, Moment.js comes with English language strings. If you need other languages, you can load them into Moment.js for later use.
To load a language, pass the key and the string values to moment.lang.
More details on each of the parts of the language bundle can be found in the customization section.
moment.lang('fr', {
months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"),
monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"),
weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"),
weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"),
weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "DD/MM/YYYY",
LL : "D MMMM YYYY",
LLL : "D MMMM YYYY LT",
LLLL : "dddd D MMMM YYYY LT"
},
calendar : {
sameDay: "[Aujourd'hui à] LT",
nextDay: '[Demain à] LT',
nextWeek: 'dddd [à] LT',
lastDay: '[Hier à] LT',
lastWeek: 'dddd [dernier à] LT',
sameElse: 'L'
},
relativeTime : {
future : "dans %s",
past : "il y a %s",
s : "quelques secondes",
m : "une minute",
mm : "%d minutes",
h : "une heure",
hh : "%d heures",
d : "un jour",
dd : "%d jours",
M : "un mois",
MM : "%d mois",
y : "une année",
yy : "%d années"
},
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'ème');
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
Once you load a language, it becomes the active language. To change active languages, simply call moment.lang with the key of a loaded language.
moment.lang('fr');
moment(1316116057189).fromNow() // il y a une heure
moment.lang('en');
moment(1316116057189).fromNow() // an hour ago
moment().lang(String);
A global language configuration can be problematic when passing around moments that may need to be formatted into different languages.
In 1.7.0 we added instance specific language configurations.
moment.lang('en'); // default the language to English
var globalLang = moment();
var localLang = moment();
localLang.lang('fr'); // set this instance to use French
localLang.format('LLLL'); // dimanche 15 juillet 2012 11:01
globalLang.format('LLLL'); // Sunday, July 15 2012 11:01 AM
moment.lang('es'); // change the global language to Spanish
localLang.format('LLLL'); // dimanche 15 juillet 2012 11:01
globalLang.format('LLLL'); // Domingo 15 Julio 2012 11:03
localLang.lang(false); // reset the instance language
localLang.format('LLLL'); // Domingo 15 Julio 2012 11:03
globalLang.format('LLLL'); // Domingo 15 Julio 2012 11:03
If you call moment#lang with no parameters, you get back the language configuration that would be used for that moment.
var fr = moment().lang('fr');
fr.lang().months // ["janvier", "février", "mars", ...]
fr.lang('en');
fr.lang().months // ["January", "February", "March", ...]
If you need to access the language data for a moment, this is the preferred way to do so.
moment.lang(String);
Loading languages in NodeJS is super easy. If there is a language file in moment/lang/ named after that key, the first call to moment.lang will load it.
var moment = require('moment');
moment.lang('fr');
moment(1316116057189).fromNow(); // il y a une heure
If you want your language supported, create a pull request to the develop branch with the required language and unit test files.
moment.lang(String, Object);
Loading languages in the browser just requires you to include the language files.
<script src="moment.min.js"></script>
<script src="lang/fr.js"></script>
<script src="lang/pt.js"></script>
There are minified versions of each of these languages. There is also a minified version of all of the languages bundled together.
<script src="moment.min.js"></script>
<script src="lang/all.min.js"></script>
Ideally, you would bundle all the files you need into one file to minimize http requests.
<script src="moment-fr-it.min.js"></script>
To add your language to Moment.js, submit a pull request with both a language file and a test file. You can find examples in moment/lang/fr.js and moment/test/lang/fr.js.
To run the tests in Node.js, do npm install, then grunt.
If all the tests pass, submit a pull request, and thank you for contributing!
moment.lang();
If you are changing languages frequently, you may want to know what language is currently being used. This is as simple as calling moment.lang without any parameters.
moment.lang('en'); // set to english
moment.lang(); // returns 'en'
moment.lang('fr'); // set to french
moment.lang(); // returns 'fr'
Moment.js is very easy to customize. In general, you should create a language setting with your customizations.
moment.lang('en-my-settings', {
// customizations.
});
However, you can also overwrite an existing language that has been loaded as well.
moment.lang('en', {
// customizations
});
Any settings that are not defined are inherited from the default english settings.
moment.lang('en', {
months : String[]
});
moment.lang('en', {
months : Function
});
Language#months should be an array of the month names.
moment.lang('en', {
months : [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
});
If you need more processing to calculate the name of the month, (for example, if there is different grammar for different formats), Language#months can be a function with the following signature. It should always return a month name.
moment.lang('en', {
months : function (momentToFormat, format) {
// momentToFormat is the moment currently being formatted
// format is the formatting string
if (/^MMMM/.test(format)) { // if the format starts with 'MMMM'
return nominative[momentToFormat.month()];
} else {
return subjective[momentToFormat.month()];
}
}
});
moment.lang('en', {
monthsShort : String[]
});
moment.lang('en', {
monthsShort : Function
});
Language#monthsShort should be an array of the month abbreviations.
moment.lang('en', {
monthsShort : [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
});
Like Language#months, Language#monthsShort can be a callback function as well.
moment.lang('en', {
monthsShort : function (momentToFormat, format) {
if (/^MMMM/.test(format)) {
return nominative[momentToFormat.month()];
} else {
return subjective[momentToFormat.month()];
}
}
});
moment.lang('en', {
weekdays : String[]
});
moment.lang('en', {
weekdays : Function
});
Language#weekdays should be an array of the weekdays names.
moment.lang('en', {
weekdays : [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
]
});
Language#weekdays can be a callback function as well.
moment.lang('en', {
weekdays : function (momentToFormat, format) {
return weekdays[momentToFormat.day()];
}
});
moment.lang('en', {
weekdaysShort : String[]
});
moment.lang('en', {
weekdaysShort : Function
});
Language#weekdaysShort should be an array of the weekdays abbreviations.
moment.lang('en', {
weekdaysShort : ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
});
Language#weekdaysShort can be a callback function as well.
moment.lang('en', {
weekdaysShort : function (momentToFormat, format) {
return weekdaysShort[momentToFormat.day()];
}
});
moment.lang('en', {
weekdaysMin : String[]
});
moment.lang('en', {
weekdaysMin : Function
});
Language#weekdaysMin should be an array of two letter weekday abbreviations. The purpose of these is for things like calendar pickers, thus they should be as small as possible.
moment.lang('en', {
weekdaysMin : ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]
});
Language#weekdaysMin can be a callback function as well.
moment.lang('en', {
weekdaysMin : function (momentToFormat, format) {
return weekdaysMin[momentToFormat.day()];
}
});
moment.lang('en', {
longDateFormat : Object
});
Language#longDateFormat should be an object containing a key/value pair for each long date format L LL LLL LLLL LT. LT should be the time format, and is also used for moment#calendar.
moment.lang('en', {
longDateFormat : {
LT: "h:mm A",
L: "MM/DD/YYYY",
l: "M/D/YYYY",
LL: "MMMM Do YYYY",
ll: "MMM D YYYY",
LLL: "MMMM Do YYYY LT",
lll: "MMM D YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT",
llll: "ddd, MMM D YYYY LT"
}
});
You can eliminate the lowercase l tokens and they will be created automatically by replacing long tokens with the short token variants.
moment.lang('en', {
longDateFormat : {
LT: "h:mm A",
L: "MM/DD/YYYY",
LL: "MMMM Do YYYY",
LLL: "MMMM Do YYYY LT",
LLLL: "dddd, MMMM Do YYYY LT"
}
});
moment.lang('en', {
relativeTime : Object
});
Language#relativeTime should be an object of the replacement strings for moment#from.
moment.lang('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: "seconds",
m: "a minute",
mm: "%d minutes",
h: "an hour",
hh: "%d hours",
d: "a day",
dd: "%d days",
M: "a month",
MM: "%d months",
y: "a year",
yy: "%d years"
}
});
Language#relativeTime.future refers to the prefix/suffix for future dates, and Language#relativeTime.past refers to the prefix/suffix for past dates. For all others, a single character refers to the singular, and an double character refers to the plural.
If a language requires additional processing for a token, It can set the token as a function with the following signature.
The function should return a string.
function (number, withoutSuffix, key, isFuture) {
return string;
}
The key argument refers to the replacement key in the Language#relativeTime object. (eg. s m mm h, etc.)
The number argument refers to the number of units for that key. For m, the number is the number of minutes, etc.
The withoutSuffix argument will be true if the token will be displayed without a suffix, and false if it will be displayed with a suffix. (The reason for the inverted logic is because the default behavior is to display with the suffix.)
The isFuture argument will be true if it is going to use the future suffix/prefix and false if it is going to use the past prefix/suffix. The isFuture argument was added in version 1.6.0.
moment.lang('en', {
meridiem : Function
});
If your language uses 'am/pm', Language#meridiem can be ommitted, as those values are the defaults.
If your language needs any different computation for am/pm, Language#meridiem should be a callback function that returns the correct string based on hour, minute, and upper/lowercase.
moment.lang('en', {
meridiem : function (hour, minute, isLowercase) {
if (hour < 9) {
return "早上";
} else if (hour < 11 && minute < 30) {
return "上午";
} else if (hour < 13 && minute < 30) {
return "中午";
} else if (hour < 18) {
return "下午";
} else {
return "晚上";
}
}
});
Before version 1.6.0, Language#meridiem was a map of upper and lowercase versions of am/pm.
moment.lang('en', {
meridiem : {
am : 'am',
AM : 'AM',
pm : 'pm',
PM : 'PM'
}
});
This has been deprecated. The 1.6.0 callback function syntax is now used instead.
moment.lang('en', {
calendar : Object
});
Language#calendar should have the following formatting strings.
moment.lang('en', {
calendar : {
lastDay : '[Yesterday at] LT',
sameDay : '[Today at] LT',
nextDay : '[Tomorrow at] LT',
lastWeek : '[last] dddd [at] LT',
nextWeek : 'dddd [at] LT',
sameElse : 'L'
}
});
Each of the Language#calendar keys can also be a callback function with the scope of the current moment. It should return a formatting string.
function () {
return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
moment.lang('en', {
ordinal : Function
});
Language#ordinal should be a function that returns the ordinal for a given number.
moment.lang('en', {
ordinal : function (number) {
var b = number % 10;
var output = (~~ (number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
return number + output;
}
});
As of 2.0.0, the ordinal function should return both the number and the ordinal. Previously, only the ordinal was returned.
For more information on ordinal numbers, see wikipedia
Moment.js also has duration objects. Where a moment is defined as single points in time, durations are defined as a length of time.
Durations do not have a defined beginning and end date. They are contextless.
A duration is conceptually more similar to '2 hours' than to 'between 2 and 4 pm today'. As such, they are not a good solution to converting between units that depend on context.
For example, a year can be defined as 366 days, 365 days, 365.25 days, 1 months, or 52 weeks. Trying to convert years to days makes no sense without context. It is much better to use moment#diff for calculating days or years between two moments that to use Durations.
moment.duration(Number, String);
moment.duration(Number);
moment.duration(Object);
To create a duration, call moment.duration() with the length of time in milliseconds.
moment.duration(100); // 100 milliseconds
If you want to create a moment with a unit of measurement other than seconds, you can pass the unit of measurement as well.
moment.duration(2, 'seconds');
moment.duration(2, 'minutes');
moment.duration(2, 'hours');
moment.duration(2, 'days');
moment.duration(2, 'weeks');
moment.duration(2, 'months');
moment.duration(2, 'years');
The same shorthand for moment#add and moment#subtract works here as well.
| Key | Shorthand |
|---|---|
| years | y |
| months | M |
| weeks | w |
| days | d |
| hours | h |
| minutes | m |
| seconds | s |
| milliseconds | ms |
Much like moment#add, you can pass an object of values if you need multiple different units of measurement.
moment.duration({
seconds: 2,
minutes: 2,
hours: 2,
days: 2,
weeks: 2,
months: 2,
years: 2
});
moment.duration().humanize();
Sometimes, you want all the goodness of moment#from but you don't want to have to create two moments, you just want to display a length of time.
Enter moment.duration().humanize().
moment.duration(1, "minutes").humanize(); // a minute
moment.duration(2, "minutes").humanize(); // 2 minutes
moment.duration(24, "hours").humanize(); // a day
By default, the return string is suffixless. If you want a suffix, pass in true as seen below.
moment.duration(1, "minutes").humanize(true); // in a minute
For suffixes before now, pass in a negative number.
moment.duration(-1, "minutes").humanize(true); // a minute ago
moment.duration().milliseconds();
moment.duration().asMilliseconds();
To get the number of milliseconds in a duration, use moment.duration().milliseconds().
It will return a number between 0 and 1000.
moment.duration(500).milliseconds(); // 500
moment.duration(1500).milliseconds(); // 500
moment.duration(15000).milliseconds(); // 0
If you want the length of the duration in milliseconds, use moment.duration().asMilliseconds() instead.
moment.duration(500).asMilliseconds(); // 500
moment.duration(1500).asMilliseconds(); // 1500
moment.duration(15000).asMilliseconds(); // 15000
moment.duration().seconds();
moment.duration().asSeconds();
To get the number of seconds in a duration, use moment.duration().seconds().
It will return a number between 0 and 60.
moment.duration(500).seconds(); // 0
moment.duration(1500).seconds(); // 1
moment.duration(15000).seconds(); // 15
If you want the length of the duration in seconds, use moment.duration().asSeconds() instead.
moment.duration(500).asSeconds(); // 0.5
moment.duration(1500).asSeconds(); // 1.5
moment.duration(15000).asSeconds(); // 15
moment.duration().minutes();
moment.duration().asMinutes();
As with the other getters for durations, moment.duration().minutes() gets the minutes (0 - 60).
moment.duration().asMinutes() gets the length of the duration in minutes.
moment.duration().hours();
moment.duration().asHours();
As with the other getters for durations, moment.duration().hours() gets the hours (0 - 24).
moment.duration().asHours() gets the length of the duration in hours.
moment.duration().days();
moment.duration().asDays();
As with the other getters for durations, moment.duration().days() gets the days (0 - 30).
moment.duration().asDays() gets the length of the duration in days.
moment.duration().months();
moment.duration().asMonths();
As with the other getters for durations, moment.duration().months() gets the months (0 - 12).
moment.duration().asMonths() gets the length of the duration in months.
Note: The length of a duration in months is defined as 30 days.
moment.duration().years();
moment.duration().asYears();
As with the other getters for durations, moment.duration().years() gets the years.
moment.duration().asYears() gets the length of the duration in years.
Note: The length of a duration in years is defined as 365 days.
Some other people have made plugins for Moment.js that may be useful to you.
npm install moment-strftime
If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes' plugin moment-strftime.
The repository is located at github.com/benjaminoakes/moment-strftime
npm install moment-isocalendar
If you are looking for a Python-like isocalendar method, you can use Rocky Meza's plugin
moment-isocalendar
Calling the isocalendar method on a moment will return an array like the following:
[year, week_of_year, day_of_week, minutes_since_midnight]
moment().isocalendar(); // [2012, 8, 5, 870]
You can also reconstruct a moment from a isocalendar array.
moment.fromIsocalendar([2011, 51, 5, 870]).format('LLLL');
// "Friday, December 23 2011 2:30 PM"
The repository is located at github.com/fusionbox/moment-isocalendar
npm install moment-range
If you need to work with date ranges, you can use Gianni Chiappetta's plugin moment-range.
Documentation can be found on the homepage gf3.github.com/moment-range.
And it is also available for the web at the repository below.
The repository is located at github.com/gf3/moment-range
npm install twix
Another range plugin is Isaac Cambron's library Twix. It has many
range-related features and excels at formatting ranges readably. For example,
var t = moment("1/25/1982 9:30 AM").twix("1/25/1982 1:30 PM");
t.isCurrent(); //=> false
t.count('minutes'); //=> 241
t.format(); //=> 'Jan 25, 1982, 9:30 AM - 1:30 PM'
t.simpleFormat("h:m"); //=> '9:30 - 1:30'
Full documentation of all the options and features is here.
It's available on npm like so:
npm install twix
Or just grab the JS file from here.
If you're trying to format times for tweets like the way Twitter does, you can use the moment.twitter plugin by @hijonathan.
It's a simple way to display both short and long versions of human-readable timestamps.
moment().subtract('hours', 5).twitter();
// 5 hours
Yes, it does smart pluralization.
moment().subtract('hour', 1).twitter();
// 1 hour
Not short enough for you?
moment().subtract('days', 6).twitterShort();
// 6d