moment js количество дней между датами
Moment js количество дней между датами
В этой рубрике Вы найдете уроки по Javascript библиотеке jQuery.
Анимация набора текста на jQuery
Сегодня мы бы хотели вам рассказать о библиотеке TypeIt — бесплатном jQuery плагине. С её помощью можно имитировать набор текста. Если всё настроить правильно, то можно добиться очень реалистичного эффекта.
Временная шкала на jQuery
jQuery плагин для создания временной шкалы.
Заметка: Перезагрузка и редирект на JavaScript
Быстрая заметка, где вы сможете найти парочку JS сниппетов для перезагрузки и перенаправления пользователей через JavaScript.
Рисуем диаграмму Ганта
jQuery плагин для создания диаграммы Ганта.
AJAX и PHP: загрузка файла
Пример того как осуществить загрузку файла через PHP и jQuery ajax.
Stimed — стили в зависимости от времени суток
Интересная библиотека с помощью которой можно задать определённым элементам страницы особые стили в зависимости от времени суток.
jQuery плагин для отображения превью загружаемого файла
Небольшой jQuery плагин, который позволит увидеть миниатюру изображения ещё до загрузки на сервер.
Как рассчитать количество «рабочих дней» между двумя датами в Javascript с помощью moment.js?
Как рассчитать количество рабочих дней между двумя датами в JavaScript с помощью moment.js. У меня есть рабочая формула, которая вычисляет эти дни, но формула не удовлетворяет всем условиям:
Я получаю пять дней за 7 дней, потому что суббота и воскресенье считаются нерабочими днями, но эта формула не будет работать, если подсчет дней начался с воскресенья или субботы.
Пожалуйста, любой может помочь в этом отношении, что необходимо внести необходимые изменения, чтобы избежать этой проблемы.
6 ответов
Просто разделите его на 3 части: первая неделя, последняя неделя и промежуточное, что-то вроде этого:
Вывод тестового кода:
Вы можете попробовать это (без цикла):
Я использую простую функцию для достижения этой цели. Может быть, не самый эффективный, но это работает. Это не требует Moment.js. это просто Javascript.
Для addDays я использую следующую функцию:
Используя momentjs, это возможно следующим образом:
Начало недели было 15/10/2017 00:00 UTC или 14/10/2017 21: 00-03: 00
Конец недели был 22/10/2017 00:00 UTC или 21/10/2017 22: 00-02: 00 (летнее время)
Поэтому вместо 7 разница между «первой» и «последней» переменной в днях составляла 6 (или 8, в зависимости от вашего часового пояса).
Код исправлен ниже:
Я обнаружил, что ответ Кокиццу не сработал, если бы дни были на одной неделе (например, солнце до сидения), поэтому согласился на это:
Как узнать количество дней между двумя датами в JavaScript?
Как узнать количество дней между двумя датами в JavaScript? Например, в полях ввода указаны две даты:
30 ответов
Вот быстрая и грязная реализация datediff в качестве доказательства концепции для решения проблемы, представленной в вопросе. Он основан на том факте, что вы можете получить прошедшие миллисекунды между двумя датами, вычитая их, что приводит их к значению их примитивного числа (миллисекунды с начала 1970 года).
Вы должны знать, что «нормальные» API-интерфейсы Date (без «UTC» в названии) работают в локальном часовом поясе браузера пользователя, поэтому в целом вы можете столкнуться с проблемами, если ваш пользователь находится в часовом поясе, который вы не делаете. ожидайте, и ваш код будет иметь дело с переходами на летнее время. Вам следует внимательно прочитать документацию по объекту Date и его методам, а для чего-либо более сложного настоятельно рекомендуем использовать библиотеку, которая предлагает более безопасные и мощные API для манипулирования датами.
Простой способ подсчета дней между двумя датами состоит в том, чтобы удалить оба их компонента времени, то есть установить часы, минуты, секунды и миллисекунды в 0, а затем вычесть их время и погрузить его с миллисекундами, равными одному дню.
Если вы хотите иметь DateArray с датами, попробуйте это:
Значения даты в JS являются значениями даты и времени.
Таким образом, прямые вычисления даты противоречивы:
Например нам нужно конвертировать 2-ую дату:
Метод можно обрезать мельницы в обе даты:
Возможно, это не самое элегантное решение, но, кажется, оно отвечает на вопрос относительно простым кусочком кода, я думаю. Разве вы не можете использовать что-то вроде этого:
Предполагается, что вы передаете объекты даты в качестве параметров.
Я использовал приведенный ниже код, чтобы поэкспериментировать с функциональностью даты публикации для публикации новостей. Я рассчитываю минуту, час, день или год на основе даты публикации и текущей даты.
Как насчет использования formatDate из виджета DatePicker? Вы можете использовать его для преобразования дат в формат отметки времени (миллисекунды с 01.01.1970), а затем выполнить простое вычитание.
Самый простой способ получить разницу между двумя датами:
Вы получаете разницу дней (или NaN, если один или оба не могут быть проанализированы). Дата разбора дала результат в миллисекундах, и чтобы получить его по дням, нужно разделить его на 24 * 60 * 60 * 1000
Если вы хотите, чтобы оно делилось на дни, часы, минуты, секунды и миллисекунды:
Вот моя переработанная версия Джеймса:
На момент написания статьи только один из остальных ответов правильно обрабатывал переходы DST (летнее время). Вот результаты для системы, расположенной в Калифорнии:
Хотя Math.round возвращает правильные результаты, я думаю, что это несколько неуклюже. Вместо этого, явно учитывая изменения в смещении UTC, когда начинается или заканчивается DST, мы можем использовать точную арифметику:
Объяснение
Вычисление дат в JavaScript сложно, потому что Date объекты хранят время внутри UTC, а не по местному времени. Например, 3/10/2013 12:00 по тихоокеанскому стандартному времени (UTC-08: 00) хранится как 3/10/2013 8:00 по UTC и 11.03.2013 в 12:00 по тихоокеанскому летнему времени ( UTC-07: 00) хранится как 11.03.2013 7:00 UTC. В этот день с полуночи до полуночи по местному времени в UTC только 23 часа!
Хотя день по местному времени может иметь больше или меньше 24 часов, день в UTC всегда равен 24 часам. 1 Показанный выше метод daysBetween использует этот факт, сначала вызывая treatAsUTC для корректировки местного времени до полуночи UTC перед вычитанием и делением.
1. JavaScript игнорирует дополнительные секунды.
Как получить количество дней между двумя датами в JavaScript?
Как получить количество дней между двумя датами в JavaScript? Например, учитывая две даты в полях ввода:
30 ответов
вы должны знать, что» нормальные «API даты (без» UTC » в имени) работают в локальном часовом поясе браузера пользователя, поэтому в целом вы можете столкнуться с проблемами, если ваш пользователь находится в часовом поясе, который вы не ожидаете, и вашему коду придется иметь дело с переходами на летнее время. Вы должны внимательно прочитать документацию для объекта Date и его методов, а для чего-либо более сложного настоятельно рассмотреть возможность использования библиотеки, которая предлагает более безопасные и мощные API для манипулирования датой.
кроме того, для иллюстрации, фрагмент используется им доступ на window объект для краткости, но в производстве вы должны использовать стандартизированные API, такие как getElementById, или, что более вероятно, некоторые рамки пользовательского интерфейса.
на момент написания этой статьи только один из других ответов правильно обрабатывает переходы DST (летнее время). Вот результаты по системе, расположенной в Калифорнии:
хотя Math.round возвращает правильные результаты, я думаю, что это немного неуклюжим. Вместо этого, явно учитывая изменения смещения UTC, когда DST начинается или заканчивается, мы можем использовать точную арифметику:
объяснение
вычисления даты JavaScript сложны потому что Date объекты хранят время внутри в UTC, а не по местному времени. Например, 3/10/2013 12: 00 am Pacific Standard Time (UTC-08:00) хранится как 3/10/2013 8:00 AM UTC, а 3/11/2013 12:00 am Pacific Daylight Time (UTC-07:00) хранится как 3/11/2013 7:00 AM UTC. В этот день с полуночи до полуночи местное время составляет всего 23 часа в UTC!
хотя день по местному времени может иметь более или менее 24 часов, день в UTC всегда ровно 24 часа. 1 на daysBetween метод, показанный выше, использует этот факт, сначала вызывая treatAsUTC чтобы настроить оба местных времени до полуночи UTC, перед вычитанием и делением.
1. JavaScript игнорирует високосные секунды.
самый простой способ получить разницу между двумя датами:
вы получаете разницу дней (или NaN, если один или оба не могут быть проанализированы). Дата разбора дала результат в миллисекундах, и чтобы получить его днем, вы должны разделить его на 24 * 60 * 60 * 1000
Если вы хотите разделить его на дни, часы, минуты, секунды и миллисекунды:
вот мой переделанный вариант Джеймса версия:
Я рекомендую использовать момент.библиотека js (http://momentjs.com/docs/#/displaying/difference/). Он правильно обрабатывает летнее время и в целом отлично подходит для работы.
Я бы пошел вперед и возьмите эту небольшую утилиту и в ней вы найдете функции для этого для вас. Вот краткий пример:
значения даты в JS являются значениями datetime.
таким образом, прямые вычисления даты несовместимы:
например, нам нужно преобразовать de 2-ю дату:
метод может быть усекать мельницы в обе даты:
для расчета дней между 2 даты вы можете использовать следующий код.Даты я использую здесь 01 января 2016 по 31 декабря 2016
лучше избавиться от DST, Math.сейл, математика.пол и т. д. используя время UTC:
этот пример дает разницу 109 дней. 24*60*60*1000 один день в миллисекундах.
Как насчет использования formatDate из виджета DatePicker? Вы можете использовать его для преобразования дат в формате метки времени (миллисекунды с 01/01/1970), а затем выполнить простое вычитание.
я нашел этот вопрос, когда я хочу сделать некоторые вычисления на две даты, но дата имеет значение часов и минут, я изменил ответ @michael-liu в соответствии с моим требованием, и он прошел мой тест.
diff дней 2012-12-31 23:00 и 2013-01-01 01:00 должно равняться 1. (2-часовой) дифф дней 2012-12-31 01:00 и 2013-01-01 23:00 должно равняться 1. (46 час)
Я думаю, что решения не являются правильными 100% я бы использовал ceil вместо Пол, раунд будет работать, но это не правильно операцию.
можно рассчитать полную разницу дней доказательства между двумя датами, покоящимися на разных TZs, используя следующую формулу:
будьте осторожны, когда через миллисекунд.
на дата.методов gettime() возвращает миллисекунды и делаю математическая операция с миллисекундами требует включения
Moment.js Documentation
Project Status
Moment.js has been successfully used in millions of projects, and we are happy to have contributed to making date and time better on the web. As of September 2020, Moment gets over 12 million downloads per week! However, Moment was built for the previous era of the JavaScript ecosystem. The modern web looks much different these days. Moment has evolved somewhat over the years, but it has essentially the same design as it did when it was created in 2011. Given how many projects depend on it, we choose to prioritize stability over new features.
As an example, consider that Moment objects are mutable. This is a common source of complaints about Moment. We address it in our usage guidance but it still comes as a surprise to most new users. Changing Moment to be immutable would be a breaking change for every one of the projects that use it. Creating a «Moment v3» that was immutable would be a tremendous undertaking and would make Moment a different library entirely. Since this has already been accomplished in other libraries, we feel that it is more important to retain the mutable API.
Another common argument against using Moment in modern applications is its size. Moment doesn’t work well with modern «tree shaking» algorithms, so it tends to increase the size of web application bundles. If one needs internationalization or time zone support, Moment can get quite large. Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object, codified as ECMA-402. Libraries like Luxon (and others) take advantage of this, reducing or removing the need to ship your own data files.
Recently, Chrome Dev Tools started showing recommendations for replacing Moment for the size alone. We generally support this move.
You may also want to read:
The Moment team has discussed these issues at length. We recognize that many existing projects may continue to use Moment, but we would like to discourage Moment from being used in new projects going forward. Instead, we would like to recommend alternatives that are excellent choices for use in modern applications today. We would also like to promote the Temporal addition to the JavaScript language, which is looking for feedback and contributors.
We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.
In practice, this means:
With specific regard to Moment’s internationalization locale files:
However, since we understand that Moment is well established in millions of existing projects:
Reasons to keep using Moment
In most cases, you should not choose Moment for new projects. However there are some possible reasons you might want to keep using it.
Browser support
Moment works well on Internet Explorer 8 and higher. By contrast, Luxon only works on IE 10 and higher and requires a polyfill to do so. You can read more in Luxon’s documentation.
Other libraries have also had issues with Safari, especially on mobile devices. If you have a strong requirement to support older browsers, then you might want to stick with Moment for a bit longer.
However, Day.js reports compatibility with IE8 and higher so you still may wish to consider that alternative.
Dependency by other libraries
Several other libraries, especially date pickers and graphing libraries, take Moment as a dependency. If you are using such a component and cannot find an alternative, then you are already including Moment in your project. Thus, it might make sense to continue using Moment throughout your project rather than including yet another date and time library.
Familiarity
If you are a long-time user of Moment, you may already understand its API and limitations well. If so, and the aforementioned issues are not a concern for you, then you certainly can continue to use it.
Recommendations
There are several great options to consider using instead of Moment.
When choosing, consider that:
Here are the alternatives we recommend:
Luxon
Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.
Day.js
Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment’s API and want to get moving quickly, consider using Day.js.
date-fns
Date-fns offers a series of functions for manipulating JavaScript Date objects. For more details, scroll to «Why date-fns?» on the date-fns home page.
js-Joda
No Library
JavaScript has always had a Date object, defined ECMAScript (ECMA-262) specification here.
When using Date objects, be aware of the following:
The Date object internally represents a Unix timestamp with millisecond precision. It offers functions that will convert to and from the system’s local time zone, but it is always UTC internally. Unlike a Moment object, it can not be set to use another time zone; It has no concept of «mode».
When using the Intl object, be aware of the following:
If the Date and Intl objects meet your needs and you fully understand their limitations, then you might consider using them directly.
The Future
The effort to make better date and time APIs in the JavaScript language is being done via The ECMA TC39 Temporal Proposal. It is currently at Stage 3 of the TC39 process.
You can try out Temporal today, via a non-production polyfill. Please give it a try, but don’t use it in production (yet)!
Using Moment
Moment was designed to work both in the browser and in Node.js.
All code should work in both of these environments, and all unit tests are run in both of these environments.
Currently, the following browsers are used for the ci system: Chrome on Windows XP, IE 8, 9, and 10 on Windows 7, IE 11 on Windows 10, latest Firefox on Linux, and latest Safari on OSX 10.8 and 10.11.
If you want to try the sample codes below, just open your browser’s console and enter them.
Node.js
Note: if you want to work with a particular variation of moment timezone, for example using only data from 2012-2022, you will need to import it from the builds directory like so:
Note: In 2.4.0, the globally exported moment object was deprecated. It will be removed in next major release.
Browser
Moment.js is available on cdnjs.com and on jsDelivr.
Bower
Require.js
We strongly recommend reading this if you plan to use moment with Require.js. Also upgrade to 2.14.0 or above for best experience.
For more complicated use cases please read excellent explanation by @jrburke.
Moment will still create a moment global, which is useful to plugins and other third-party code. If you wish to squash that global, use the noGlobal option on the module config.
If you don’t specify noGlobal then the globally exported moment will print a deprecation warning. From next major release you’ll have to export it yourself if you want that behavior.
For version 2.5.x, in case you use other plugins that rely on Moment but are not AMD-compatible you may need to add wrapShim: true to your r.js config.
Note: From version 2.9.0 moment exports itself as an anonymous module, so if you’re using only the core (no locales / plugins), then you don’t need config if you put it on a non-standard location.
NuGet
meteor
Browserify
Note: There is a bug that prevents moment.locale from being loaded.
Use the workaround below
In order to include all the locales
Webpack
Note: By default, webpack bundles all Moment.js locales (in Moment.js 2.18.1, that’s 160 minified KBs). To strip unnecessary locales and bundle only the used ones, add moment-locales-webpack-plugin :
There are other resources to optimize Moment.js with webpack, for example this one.
Typescript 2.13.0+
As of version 2.13.0, Moment includes a typescript definition file.
Import and use in your Typescript file
Note: If you have trouble importing moment
For Typescript 2.x try adding «moduleResolution»: «node» in compilerOptions in your tsconfig.json file
For Typescript 1.x try adding «allowSyntheticDefaultImports»: true in compilerOptions in your tsconfig.json file and then use the syntax
Locale Import
To use moment.locale you first need to import the language you are targeting.
System.js
To load moment, place it in the path specified by your System.config in the baseURL configuration. Then import it into your page.
If you need moment to be loaded as global, you can do this with the meta configuration:
Alternatively, to provide Moment as a global to only a specific dependency, you can do this:
Other
To use under Java/Rhino, see these instructions.
To use in Demandware, see these instructions.
Troubleshooting
If you are having any troubles, the first place to check is the guides.
If you don’t find what you are looking for there, try asking a question on Stack Overflow with the momentjs tag.
Note: More than half of the issues seen on Stack Overflow can be answered by this blog post.
You can also use the GitHub issue tracker to find related issues or open a new issue.
In addition, Moment has a Gitter where the internal team is frequently available.
For general troubleshooting help, Stack Overflow is the preferred forum. Moment’s maintainers are very active on Stack Overflow, as are several other knowledgeable users. The fastest response will be there.
Parse
Please read:
Now 1.0.0+
To get the current date and time, just call moment() with no parameters.
Note: From version 2.14.0, moment([]) and moment(<>) also return now. They used to default to start-of-today before 2.14.0, but that was arbitrary so it was changed.
Note: Moments are created at evaluation time, so moment().diff(moment()) may not always return 0. See this GitHub issue for more details.
String 1.0.0+
When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.
Warning: Browser support for parsing strings 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 consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
Supported ISO 8601 strings
An ISO 8601 string requires a date part.
A time part can also be included, separated from the date part by a space or an uppercase T.
Any of the date parts can have a time part.
Note: Support for the week and ordinal formats was added in version 2.3.0.
The RFC 2822 date time format
Before parsing a RFC 2822 date time the string is cleansed to remove any comments and/or newline characters. The additional characters are legal in the format but add nothing to creating a valid moment instance.
After cleansing, the string is validated in the following space-separated sections, all using the English language:
[*] See section 4.3 of the specification for details.
The parser also confirms that the day-of-week (when included) is consistent with the date.
String + Format 1.0.0+
If you know the format of an input string, you can use that to parse a moment.
The parser ignores non-alphanumeric characters by default, so both of the following will return the same thing.
You may get unexpected results when parsing both date and time. The below example may not parse as you expect:
You can use strict mode, which will identify the parsing error and set the Moment object as invalid:
Year, month, and day tokens
Tokens are case-sensitive.
Input | Example | Description |
---|---|---|
YYYY | 2014 | 4 or 2 digit year. Note: Only 4 digit can be parsed on strict mode |
YY | 14 | 2 digit year |
Y | -25 | Year with any number of digits and sign |
Q | 1..4 | Quarter of year. Sets month to first month in quarter. |
M MM | 1..12 | Month number |
MMM MMMM | Jan..December | Month name in locale set by moment.locale() |
D DD | 1..31 | Day of month |
Do | 1st..31st | Day of month with ordinal |
DDD DDDD | 1..365 | Day of year |
X | 1410715640.579 | Unix timestamp |
x | 1410715640579 | Unix ms timestamp |
YYYY from version 2.10.5 supports 2 digit years, and converts them to a year near 2000 (same as YY ).
Y was added in 2.11.1. It will match any number, signed or unsigned. It is useful for years that are not 4 digits or are before the common era. It can be used for any year.
Week year, week, and weekday tokens
For these, the lowercase tokens use the locale aware week start days, and the uppercase tokens use the ISO week date start days.
Tokens are case-sensitive.
Input | Example | Description |
---|---|---|
gggg | 2014 | Locale 4 digit week year |
gg | 14 | Locale 2 digit week year |
w ww | 1..53 | Locale week of year |
e | 0..6 | Locale day of week |
ddd dddd | Mon. Sunday | Day name in locale set by moment.locale() |
GGGG | 2014 | ISO 4 digit week year |
GG | 14 | ISO 2 digit week year |
W WW | 1..53 | ISO week of year |
E | 1..7 | ISO day of week |
Locale aware formats
Tokens are case-sensitive.
Input | Example | Description |
---|---|---|
L | 09/04/1986 | Date (in local format) |
LL | September 4 1986 | Month name, day of month, year |
LLL | September 4 1986 8:30 PM | Month name, day of month, year, time |
LLLL | Thursday, September 4 1986 8:30 PM | Day of week, month name, day of month, year, time |
LT | 8:30 PM | Time (without seconds) |
LTS | 8:30:00 PM | Time (with seconds) |
Hour, minute, second, millisecond, and offset tokens
Tokens are case-sensitive.
From version 2.10.5: fractional second tokens length 4 up to 9 can parse any number of digits, but will only consider the top 3 (milliseconds). Use if you have the time printed with many fractional digits and want to consume the input.
Z ZZ were added in version 1.2.0.
S SS SSS were added in version 1.6.0.
X was added in version 2.0.0.
k kk were added in version 2.13.0.
Unless you specify a time zone offset, parsing a string will create a date in the current time zone.
Era Year related tokens
Tokens are case-sensitive.
Era support was added in 2.25.0. The tokens/API are still in flux.
Notes and gotchas
If the moment that results from the parsed input does not exist, moment#isValid will return false.
Moment’s parser is very forgiving, and this can lead to undesired/unexpected behavior.
For example, the following behavior can be observed:
Previous to 2.13.0 the parser exhibited the following behavior. This has been corrected.
As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.
You can use both locale and strictness.
Strict parsing is frequently the best parsing option. For more information about choosing strict vs forgiving parsing, see the parsing guide.
Parsing two digit years
By default, two digit years above 68 are assumed to be in the 1900’s and years 68 or below are assumed to be in the 2000’s. This can be changed by replacing the moment.parseTwoDigitYear method. The only argument of this method is a string containing the two years input by the user, and should return the year as an integer.
Parsing glued hour and minutes
String + Formats 1.0.0+
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.
Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:
You may also specify a locale and strictness argument. They work the same as the single format case.
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.
Special Formats 2.7.0+
ISO-8601 is a standard for time and duration display. Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment.
To specify iso-8601 parsing use moment.ISO_8601 constant.
As of version 2.20.0, the following HTML5 formats are available as constants in the moment object’s HTML5_FMT property ( moment.HTML5_FMT.* ):
Constant | Format | Example | Input Type |
---|---|---|---|
DATETIME_LOCAL | YYYY-MM-DDTHH:mm | 2017-12-14T16:34 | |
DATETIME_LOCAL_SECONDS | YYYY-MM-DDTHH:mm:ss | 2017-12-14T16:34:10 | |
DATETIME_LOCAL_MS | YYYY-MM-DDTHH:mm:ss.SSS | 2017-12-14T16:34:10.234 | |
DATE | YYYY-MM-DD | 2017-12-14 | |
TIME | HH:mm | 16:34 | |
TIME_SECONDS | HH:mm:ss | 16:34:10 | |
TIME_MS | HH:mm:ss.SSS | 16:34:10.234 | |
WEEK | GGGG-[W]WW | 2017-W50 | |
MONTH | YYYY-MM | 2017-12 |
Object 2.2.1+
You can create a moment by specifying some of the units in an object.
Omitted units default to 0 or the current date, month, and year.
day and date key both mean day-of-the-month.
date was added in 2.8.4.
String values (as shown on the last line) are supported from version 2.11.0.
Unix Timestamp (milliseconds) 1.0.0+
Unix Timestamp (seconds) 1.6.0+
Date 1.0.0+
You can create a Moment with a pre-existing native Javascript Date object.
Array 1.0.0+
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]
Any value past the year is optional, and will default to the lowest possible number.
Note: Because this mirrors the native Date parameters, months, hours, minutes, seconds, and milliseconds are all zero indexed. 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.
ASP.NET JSON Date 1.3.0+
Microsoft Web API returns JSON dates in proper ISO-8601 format by default, but older ASP.NET technologies may return 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 Clone 1.2.0+
All moments are mutable. If you want a clone of a moment, you can do so implicitly or explicitly.
Calling moment() on a moment will clone it.
Additionally, you can call moment#clone to clone a moment.
UTC 1.5.0+
By default, moment parses and displays in local time.
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.
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.
It is important to note that though the displays differ above, they are both the same moment in time.
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.
parseZone 2.3.0+
Moment’s string parsing functions like moment(string) and moment.utc(string) accept offset information if provided, but convert the resulting Moment object to local or UTC time. In contrast, moment.parseZone() parses the string but keeps the resulting Moment object in a fixed-offset timezone with the provided offset in the string.
It also allows you to pass locale and strictness arguments.
moment.parseZone is equivalent to parsing the string and using moment#utcOffset to parse the zone.
Validation 1.7.0+
Moment applies stricter initialization rules than the Date constructor.
The following parsing flags result in an invalid date:
In addition to the above, As of 2.13.0 the meridiem and parsedDateParts flags work together to determine date validity.
Additionally, if the Moment is parsed in strict mode, these flags must be empty for the Moment to be valid:
Note: Moment’s concept of validity became more strict and consistent between 2.2 and 2.3. Note: Validity is determined on moment creation. A modified moment (i.e. moment().hour(NaN) ) will remain valid.
Additionally, you can use moment#invalidAt to determine which date unit overflowed.
The return value has the following meaning:
Note: In case of multiple wrong units the first one is returned (because days validity may depend on month, for example).
Invalid Moments
If a moment is invalid, it behaves like a NaN in floating point operations.
All of the following produce invalid moments:
The following produce a localized version of ‘InvalidDate’ :
The following return false :
And these return null or NaN with some structure:
Creation Data 2.11.0+
After a moment object is created, all of the inputs can be accessed with creationData() method:
Defaults 2.2.1+
You can create a moment object specifying only some of the units, and the rest will be defaulted to the current day, month or year, or 0 for hours, minutes, seconds and milliseconds.
Defaulting to now, when nothing is passed:
Defaulting to today, when only hours, minutes, seconds and milliseconds are passed:
Defaulting to this month and year, when only days and smaller units are passed:
Defaulting to this year, if year is not specified:
Get + Set
Moment.js uses overloaded getters and setters. You may be familiar with this pattern from its 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.
If you are in UTC mode, they will map to the UTC equivalent.
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.
Note: From 2.19.0 passing NaN to any setter is a no-op. Before 2.19.0 it was invalidating the moment in a wrong way.
Millisecond 1.3.0+
Gets or sets the milliseconds.
Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds.
Second 1.0.0+
Gets or sets the seconds.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the minutes.
Minute 1.0.0+
Gets or sets the minutes.
Accepts numbers from 0 to 59. If the range is exceeded, it will bubble up to the hour.
Hour 1.0.0+
Gets or sets the hour.
Accepts numbers from 0 to 23. If the range is exceeded, it will bubble up to the day.
Date of Month 1.0.0+
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.
Note: if you chain multiple actions to construct a date, you should start from a year, then a month, then a day etc. Otherwise you may get unexpected results, like when day=31 and current month has only 30 days (the same applies to native JavaScript Date manipulation), the returned date will be the 30th of the current month (see month for more details).
Day of Week 1.3.0+
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 value given is from 0 to 6, the resulting date will be within the current (Sunday-to-Saturday) week.
If the range is exceeded, it will bubble up to other weeks.
Note: Moment#date is for the date of the month, and Moment#day is for the day of the week.
As of 2.1.0, a day name is also supported. This is parsed in the moment’s current locale.
Day of Week (Locale Aware) 2.1.0+
Gets or sets the day of the week according to the locale.
If the locale assigns Monday as the first day of the week, moment().weekday(0) will be Monday. If Sunday is the first day of the week, moment().weekday(0) will be Sunday.
ISO Day of Week 2.1.0+
Gets or sets the ISO day of the week with 1 being Monday and 7 being Sunday.
A day name is also supported. This is parsed in the moment’s current locale.
Day of Year 2.0.0+
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.
Week of Year 2.0.0+
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 for that moment.
When setting the week of the year, the day of the week is retained.
Week of Year (ISO) 2.0.0+
When setting the week of the year, the day of the week is retained.
Month 1.0.0+
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.
As of 2.1.0, a month name is also supported. This is parsed in the moment’s current locale.
Before version 2.1.0, if a moment changed months and the new month did not have enough days to keep the current day of month, it would overflow to the next month.
As of version 2.1.0, this was changed to be clamped to the end of the target month.
Quarter 2.6.0+
Gets the quarter (1 to 4).
Sets the quarter (1 to 4).
Year 1.0.0+
Gets or sets the year.
Week Year 2.1.0+
Gets or sets the week-year according to the locale.
Because the first day of the first week does not always fall on the first day of the year, sometimes the week-year will differ from the month year.
For example, in the US, the week that contains Jan 1 is always the first week. In the US, weeks also start on Sunday. If Jan 1 was a Monday, Dec 31 would belong to the same week as Jan 1, and thus the same week-year as Jan 1. Dec 30 would have a different week-year than Dec 31.
Week Year (ISO) 2.1.0+
Weeks In Year 2.6.0+
Gets the number of weeks according to locale in the current moment’s year.
Weeks In Year (ISO) 2.6.0+
Gets the number of weeks in the current moment’s year, according to ISO weeks.
Get 2.2.1+
String getter. In general
Units are case insensitive, and support plural and short forms: year (years, y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m), second (seconds, s), millisecond (milliseconds, ms).
Set 2.2.1+
Generic setter, accepting unit as first argument, and value as second:
Units are case insensitive, and support plural and short forms: year (years, y), month (months, M), date (dates, D), hour (hours, h), minute (minutes, m), second (seconds, s), millisecond (milliseconds, ms).
Object parsing was added in 2.9.0
Maximum 2.7.0+
Returns the maximum (most distant future) of the given moment instances.
With no arguments the function returns a moment instance with the current time.
From version 2.10.5, if an invalid moment is one of the arguments, the result is an invalid moment.
Minimum 2.7.0+
Returns the minimum (most distant past) of the given moment instances.
With no arguments the function returns a moment instance with the current time.
From version 2.10.5, if an invalid moment is one of the arguments, the result is an invalid moment.
Manipulate
Moment.js uses the fluent interface pattern, also known as method chaining. This allows you to do crazy things like the following.
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.
Add 1.0.0+
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.
There are some shorthand keys as well if you’re into that whole brevity thing.
Key | Shorthand |
---|---|
years | y |
quarters | Q |
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.
There are no upper limits for the amounts, so you can overload any of the parameters.
Special considerations for months and years
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.
There are also special considerations to keep in mind when adding time that crosses over daylight saving time. If you are adding years, months, weeks, or days, the original hour will always match the added hour.
Adding a month will add the specified number of months to the date.
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.
Alternatively, you can use durations to add to moments.
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
Subtract 1.0.0+
Mutates the original moment by subtracting time.
As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.
Start of Time 1.7.0+
Mutates the original moment by setting it to the start of a unit of time.
These shortcuts are essentially the same as the following.
Note: moment#startOf(‘week’) was added in version 2.0.0.
As of version 2.1.0, moment#startOf(‘week’) uses the locale aware week start day.
Note: moment#startOf(‘isoWeek’) was added in version 2.2.0.
Note: moment#startOf(‘date’) was added as an alias for day in 2.13.0
End of Time 1.7.0+
Mutates the original moment by setting it to the end of a unit of time.
Note: moment#endOf(‘week’) was added in version 2.0.0.
As of version 2.1.0, moment#endOf(‘week’) uses the locale aware week start day.
Maximum From 2.1.0, Deprecated 2.7.0
Note: This function has been deprecated in 2.7.0. Consider moment.min instead.
Limits the moment to a maximum of another moment value. So a.max(b) is the same as a = moment.min(a, b) (note that max is converted to min ).
Sometimes, server clocks are not quite in sync with client clocks. This ends up displaying humanized strings such as «in a few seconds» rather than «a few seconds ago». You can prevent that with moment#max() :
Minimum From 2.1.0, Deprecated 2.7.0
Note: This function has been deprecated in 2.7.0. Consider moment.max instead.
Limits the moment to a minimum of another moment value. So a.min(b) is the same as a = moment.max(a, b) (note that min is converted to max ).
This can be used in conjunction with moment#max to clamp a moment to a range.
Local 1.5.0+
Sets a flag on the original moment to use local time to display a moment instead of the original moment’s time.
Local can also be used to convert out of a fixed offset mode:
Passing true will change the time zone without changing the current time.
See moment.utc() for more information on UTC mode.
UTC 1.5.0+
Sets a flag on the original moment to use UTC to display a moment instead of the original moment’s time.
UTC can also be used to convert out of a fixed offset mode:
Passing true will change the time zone without changing the current time.
See moment.utc() for more information on UTC mode.
UTC offset 2.9.0++
Get or set the UTC offset in minutes.
Note: Unlike moment.fn.zone this function returns the real offset from UTC, not the reverse offset (as returned by Date.prototype.getTimezoneOffset ).
Getting the utcOffset of the current object:
It is also possible to set the UTC offset from a string.
The utcOffset function has an optional second parameter which accepts a boolean value indicating whether to keep the existing time of day.
Passing false (the default) will keep the same instant in Universal Time, but the local time will change.
Passing true will keep the same local time, but at the expense of choosing a different point in Universal Time.
One use of this feature is if you want to construct a moment with a specific time zone offset using only numeric input values:
Time zone Offset From 1.2.0, deprecated 2.9.0+
Note: This function has been deprecated in 2.9.0. Consider moment.fn.utcOffset instead.
Get the time zone offset in minutes.
As of version 2.1.0, it is possible to set the offset by passing in the number of minutes offset from GMT.
It is also possible to set the zone from a string.
Display
Once parsing and manipulation are done, you need some way to display the moment.
Format 1.0.0+
This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
X was added in 2.0.0.
e E gg gggg GG GGGG were added in 2.1.0.
x was added in 2.8.4.
SSSS to SSSSSSSSS were added in 2.10.5. They display 3 significant digits and the rest is filled with zeros.
k and kk were added in 2.13.0.
Localized formats
Because preferred formatting differs based on locale, there are a few tokens that can be used to format a moment based on its locale.
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 |
Time with seconds | LTS | 8:30:25 PM |
Month numeral, day of month, year | L | 09/04/1986 |
l | 9/4/1986 | |
Month name, day of month, year | LL | September 4, 1986 |
ll | Sep 4, 1986 | |
Month name, day of month, year, time | LLL | September 4, 1986 8:30 PM |
lll | Sep 4, 1986 8:30 PM | |
Month name, day of month, day of week, year, time | LLLL | Thursday, September 4, 1986 8:30 PM |
llll | Thu, Sep 4, 1986 8:30 PM |
l ll lll llll are available in 2.0.0. LTS was added in 2.8.4.
Escaping characters
To escape characters in format strings, you can wrap the characters in square brackets.
Similarities and differences with LDML
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 locales, see this chart of date formatting tokens.
Formatting speed
To compare Moment.js formatting speed against other libraries, check out this comparison against other libraries.
Other tokens
If you are more comfortable working with strftime instead of LDML-like parsing tokens, you can use Ben Oakes’ plugin. benjaminoakes/moment-strftime.
Default format
In certain instances, a local timezone (such as Atlantic/Reykjavik ) may have a zero offset, and will be considered to be UTC. In such cases, it may be useful to set moment.defaultFormat and moment.defaultFormatUtc to use the same formatting.
Changing the value of moment.defaultFormat will only affect formatting, and will not affect parsing. for example:
Time from now 1.0.0+
The base strings are customized by the current locale. Time is rounded to the nearest second.
The breakdown of which string is displayed for each length of time is outlined in the table below.
Note: From version 2.10.3, if the target moment object is invalid the result is the localized Invalid date string.
Note: The ss key was added in 2.18.0. It is an optional threshold. It will never display UNLESS the user manually sets the ss threshold. Until the ss threshold is set, it defaults to the value of the s threshold minus 1 (so, invisible to the user).
Time from X 1.0.0+
From version 2.10.3, if any of the endpoints are invalid the result is the localized Invalid date string.
Time to now 2.10.3+
The breakdown of which string is displayed for each length of time is outlined in the table below.
From version 2.10.3, if the target moment object is invalid the result is the localized Invalid date string.
Time to X 2.10.3+
From version 2.10.3, if any of the endpoints are invalid the result is the localized Invalid date string.
Calendar Time 1.3.0+
moment#calendar will format a date with different strings depending on how close to referenceDay ‘s date (today by default) the date is.
Last week | Last Monday at 2:30 AM |
The day before | Yesterday at 2:30 AM |
The same day | Today at 2:30 AM |
The next day | Tomorrow at 2:30 AM |
The next week | Sunday at 2:30 AM |
Everything else | 7/10/2011 |
These strings are localized, and can be customized.
From 2.10.5 moment supports specifying calendar output formats per invocation:
sameElse is used as the format when the moment is more than a week away from the referenceDay
Note: From version 2.14.0 the formats argument to calendar can be a callback that is executed within the moment context with a single argument now:
Note: From version 2.25.0 you can only pass a formats argument, it could be an object of strings and functions:
Difference 1.0.0+
To get the difference in another unit of measurement, pass that measurement as the second argument.
By default, moment#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument. Before 2.0.0, moment#diff returned a number rounded to the nearest integer, not a truncated number.
Month and year diffs
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.
This change to month and year diffs was made in 2.0.0. As of version 2.9.0 diff also support quarter unit.
Unix Timestamp (milliseconds) 1.0.0+
Unix Timestamp (seconds) 1.6.0+
moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).
This value is floored to the nearest second, and does not include a milliseconds component.
Days in Month 1.5.0+
Get the number of days in the current month.
As Javascript Date 1.0.0+
moment#native has been replaced by moment#toDate and has been deprecated as of 1.6.0.
As Array 1.7.0+
As JSON 2.0.0+
When serializing an object to JSON, if there is a Moment object, it will be represented as an ISO8601 string, adjusted to UTC.
This changes the behavior as follows:
As ISO 8601 String 2.1.0+
Formats a string to the ISO8601 standard.
From version 2.8.4 the native Date.prototype.toISOString is used if available, for performance reasons.
As Object 2.10.5+
This returns an object containing year, month, day-of-month, hour, minute, seconds, milliseconds.
As String 2.1.0+
Inspect 2.16.0+
Returns a machine readable string, that can be evaluated to produce the same moment. Because of the name its also used in node interactive shell to display objects.
Note: This function is mostly intended for debugging, not all cases are handled precisely.
Query
Is Before 2.0.0+
Check if a moment is before another moment. The first argument will be parsed as a moment, if not already so.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
Is Same 2.0.0+
Check if a moment is the same as another moment. The first argument will be parsed as a moment, if not already so.
If you want to limit the granularity to a unit other than milliseconds, pass it as the second parameter.
If the two moments have different timezones, the timezone of the first moment will be used for the comparison.
Is After 2.0.0+
Check if a moment is after another moment. The first argument will be parsed as a moment, if not already so.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
Is Same or Before 2.11.0+
Check if a moment is before or the same as another moment. The first argument will be parsed as a moment, if not already so.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
Is Same or After 2.11.0+
Check if a moment is after or the same as another moment. The first argument will be parsed as a moment, if not already so.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
Is Between 2.9.0+
Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive. The first two arguments will be parsed as moments, if not already so.
Note that the order of the two arguments matter: the «smaller» date should be in the first argument.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the third parameter.
Version 2.13.0 introduces inclusivity. A [ indicates inclusion of a value. A ( indicates exclusion. If the inclusivity parameter is used, both indicators must be passed.
Note that in the event that the from and to parameters are the same, but the inclusivity parameters are different, false will preside.
Is Daylight Saving Time 1.2.0+
moment#isDST checks if the current moment is in daylight saving time.
Is DST Shifted From 2.3.0, Deprecated 2.14.0
Note: As of version 2.14.0 this function is deprecated. It doesn’t give the right answer after modifying the moment object. For more information refer to moment/3160
Another important piece of validation is to know if the date has been moved by a DST. For example, in most of the United States:
This is because daylight saving time shifts the time from 2:00 to 3:00, so 2:30 isn’t a real time. The resulting time is browser-dependent, either adjusting the time forward or backwards. Use moment#isDSTShifted to test for this condition.
Is Leap Year 1.0.0+
moment#isLeapYear returns true if that year is a leap year, and false if it is not.
Is a Moment 1.5.0+
From version 2.11.0, you can also test for a moment object by instanceof operator:
Is a Date 2.9.0+
Moment.js has robust support for internationalization.
You can load multiple locales and easily switch between them.
In addition to assigning a global locale, you can assign a locale to a specific moment.
Changing locale globally 1.0.0+
By default, Moment.js comes with English (United States) locale strings. If you need other locales, you can load them into Moment.js for later use.
More details on each of the parts of the locale bundle can be found in the customization section.
Details about week.dow and week.doy can be found in the customization section.
Once you load a locale, it becomes the active locale. To change active locales, simply call moment.locale with the key of a loaded locale.
As of 2.21.0, Moment will console.warn if the locale is unavailable.
As of 2.8.0, changing the global locale doesn’t affect existing instances.
moment.locale returns the locale used. This is useful because Moment won’t change locales if it doesn’t know the one you specify.
You may also specify a list of locales, and Moment will use the first one it has localizations for.
Finally, Moment will search intelligently through an array of locales and their substrings.
then first «AA-BB» is tried, then a naive solution would try «AA», but this one instead checks to see that «AA-CC» is actually more concrete than «AA», so it tries «AA-CC» next, and only after it fails (if it fails) it tries «AA», because «XX-YY» does not have «AA» as prefix. So in the end the following locales are tried in this order (assuming all fail so the next one is tried):
Changing locales locally 1.7.0+
A global locale configuration can be problematic when passing around moments that may need to be formatted into different locale.
If you call moment#locale with no parameters, you get back the locale configuration that would be used for that moment.
If you need to access the locale data for a moment, this is the preferred way to do so.
As of 2.3.0, you can also specify an array of locale identifiers. It works the same way it does in the global locale configuration.
Loading locales in NodeJS 1.0.0+
Loading locales in NodeJS is super easy. If there is a locale file in moment/locale/ named after that key, import it first, then call moment.locale to load it.
To save the step of loading individual locales (i.e. just load them all), import the moment/min/moment-with-locales module instead.
If you want your locale supported, create a pull request to the develop branch with the required locale and unit test files.
Loading locales in the browser 1.0.0+
Loading locales in the browser just requires you to include the locale files. Be sure to specify the charset to prevent encoding issues.
There are minified versions of all locales together:
To minimize HTTP requests, use our Grunt task to compile Moment with a custom list of locales:
If you are using JSPM as plugin manager, you should add the locale in your lib.
Note: Locale files are defined in UMD style, so they should work seamlessly in all environments.
Adding your locale to Moment.js
If all the tests pass, submit a pull request, and thank you for contributing!
Checking the current Moment.js locale 1.6.0+
If you are changing locales frequently, you may want to know what locale is currently being used. This is as simple as calling moment.locale without any parameters.
As of version 2.12.0 it is possible to list all locales that have been loaded and are available to use:
Listing the months and weekdays of the current Moment.js locale 2.3.0+
It is sometimes useful to get the list of months or weekdays in a locale, for example when populating a dropdown menu.
Returns the list of months in the current locale.
You can pass an integer into each of those functions to get a specific month or weekday.
As of 2.13.0 you can pass a bool as the first parameter of the weekday functions. If true, the weekdays will be returned in locale specific order. For instance, in the Arabic locale, Saturday is the first day of the week, thus:
Note: Absent the locale specific parameter, weekdays always have Sunday as index 0, regardless of the local first day of the week.
Some locales make special considerations into account when formatting month names. For example, Dutch formats month abbreviations without a trailing period, but only if it’s formatting the month between dashes. The months method supports passing a format in so that the months will be listed in the proper context.
And finally, you can combine both the format option and the integer option.
Accessing locale specific functionality 2.8.0+
You can access the properties of the currently loaded locale through the moment.localeData(key) function. It returns the current locale or a locale with the given key:
The returned object has the following methods:
Details about firstDayOfYear can be found in the customization section.
Pseudo Locale 2.13.0+
As of version 2.13.0 moment optionally includes a pseudo locale. This locale will populate the dates with very obviously changed data. Pseudo locales can be useful when testing, as they make obvious what data has and has not been localized. Just include the pseudo-locale, and set moment’s locale to x-pseudo. Text from Moment will be very easy to spot.
Customize
Moment.js is very easy to customize. In general, you should create a locale setting with your customizations.
You can remove a previously defined locale by passing null as the second argument. The deleted locale will no longer be available for use.
As of 2.12.0 it is possible to create a locale that inherits from a parent locale.
Properties that are not specified in the locale will be inherited from the parent locale.
As of 2.16.0 it is possible to define a locale with a parent that hasn’t itself been defined or loaded.
As of 2.21.0 when attempting to create a moment with the newly defined locale, moment will attempt to lazy load the parent if it exists. Failing that it will default the parent to the global locale.
As of 2.12.0 it is also possible to update a locale’s properties.
Any properties specified will be updated, while others will remain the same. This function does not affect moments that already exist. Note that calling updateLocale also changes the current global locale, to the locale that is updated; see this GitHub issue for more information.
To revert an update use:
2.12.0 deprecated using moment.locale() to change an existing locale. Use moment.updateLocale() instead.
Month Names 1.0.0+
Locale#months should be an array of the month names.
If you need more processing to calculate the name of the month, (for example, if there is different grammar for different formats), Locale#months can be a function with the following signature. It should always return a month name.
Month Abbreviations 1.0.0+
Locale#monthsShort should be an array of the month abbreviations.
Weekday Names 1.0.0+
Locale#weekdays should be an array of the weekdays names.
Locale#weekdays can be a callback function as well.
Note: From version 2.11.0 format/standalone cases can be passed as well. isFormat will be used against the full format string to determine which form to use.
Weekday Abbreviations 1.0.0+
Locale#weekdaysShort should be an array of the weekdays abbreviations.
Locale#weekdaysShort can be a callback function as well.
Minimal Weekday Abbreviations 1.7.0+
Locale#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.
Locale#weekdaysMin can be a callback function as well.
Long Date Formats 1.1.0+
You can eliminate the lowercase l tokens and they will be created automatically by replacing long tokens with the short token variants.
Relative Time 1.0.0+
Locale#relativeTime.future refers to the prefix/suffix for future dates, and Locale#relativeTime.past refers to the prefix/suffix for past dates. For all others, a single character refers to the singular, and a double character refers to the plural.
If a locale requires additional processing for a token, it can set the token as a function with the following signature. The function should return a string.
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.
Note: Handling for w and ww was added in 2.25.0.
AM/PM 1.6.0+
If your locale uses ‘am/pm’, Locale#meridiem can be omitted, as those values are the defaults.
If your locale needs any different computation for am/pm, Locale#meridiem should be a callback function that returns the correct string based on hour, minute, and upper/lowercase.
AM/PM Parsing 2.1.0+
Locale#isPM should return true if the input string is past 12 noon. This is used in parsing the a A tokens.
To configure what strings should be parsed as input, set the meridiemParse property.
Calendar 1.3.0+
Locale#calendar should have the following formatting strings.
Each of the Locale#calendar keys can also be a callback function with the scope of the current moment and first argument a moment that depicts now. It should return a formatting string.
Calendar Format 2.14.0+
This lets you modify the tokens used by calendar.
Ordinal 1.0.0+
Locale#ordinal should be a function that returns the ordinal for a given number.
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.
Relative Time Thresholds 2.7.0+
unit | meaning | usage |
---|---|---|
ss | a few seconds | least number of seconds to be counted in seconds, minus 1. Must be set after setting the `s` unit or without setting the `s` unit. |
s | seconds | least number of seconds to be considered a minute. |
m | minutes | least number of minutes to be considered an hour. |
h | hours | least number of hours to be considered a day. |
d | days | least number of days to be considered a week. |
w | weeks | least number of weeks to be considered a month. Not used by default. |
M | months | least number of months to be considered a year. |
Note: Week unit was added in 2.25.0. By default it is not used (set to null), but you can set it to non-null value, and also (optionally) set d lower, so it transitions from days to weeks earlier.
Note: Retrieving thresholds was added in 2.8.1.
Note: Retrieving and setting ss threshold was added in 2.18.0.
Relative Time Rounding 2.14.0+
You can even choose to do no rounding at all:
Changing Time Source 2.11.0+
If you want to change the time that Moment sees, you can specify a method that returns the number of milliseconds since the Unix epoch (January 1, 1970).
First Day of Week and First Week of Year 1.0.0+
Eras 2.25.0+
Note: The era-related APIs are subject to change.
Invalid Date 2.3.0+
Locale#invalidDate should be a string.
Durations
Moment.js also has duration objects. Where a moment is defined as a single point in time, a duration is 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.
As discussed here, the duration format for Moment.js differs very slightly from the specifications for ISO 8601 nominal duration and RFC 5545 duration.
Creating 1.6.0+
To create a duration, call moment.duration() with the length of time in milliseconds.
If you want to create a moment with a unit of measurement other than milliseconds, you can pass the unit of measurement as well.
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 |
As of 2.1.0, moment supports parsing ASP.NET style time spans. The following formats are supported.
As of 2.3.0, moment also supports parsing ISO 8601 durations.
As of 2.11.0, duration format strings with a space between days and rest is supported.
As of 2.13.0, mixed negative and positive signs are supported when parsing durations.
As of 2.18.0, invalid durations are supported, similarly to invalid moments. To create an invalid duration you can pass NaN for a value of a unit.
In upcoming releases expect invalid durations to cover more cases (like null values for units).
Clone 2.19.0+
Create a clone of a duration. Durations are mutable, just like moment objects, so this lets you get a snapshot, at some point in time.
Humanize 1.6.0+
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.
For suffixes before now, pass in a negative number.
Humanize output can be configured with relative time thresholds. To specify thresholds for a particular invocation of humanize, pass them as a sole argument or after suffix arg:
Note: Passing thresholds in humanize was added in 2.25.0.
Milliseconds 1.6.0+
It will return a number between 0 and 999.
If you want the length of the duration in milliseconds, use moment.duration().asMilliseconds() instead.
Seconds 1.6.0+
It will return a number between 0 and 59.
If you want the length of the duration in seconds, use moment.duration().asSeconds() instead.
Minutes 1.6.0+
moment.duration().asMinutes() gets the length of the duration in minutes.
Hours 1.6.0+
moment.duration().asHours() gets the length of the duration in hours.
Days 1.6.0+
moment.duration().asDays() gets the length of the duration in days.
Weeks 1.6.0+
moment.duration().asWeeks() gets the length of the duration in weeks.
Pay attention that unlike the other getters for duration, weeks are counted as a subset of the days, and are not taken off the days count.
Note: The length of a duration in weeks is defined as 7 days.
Months 1.6.0+
moment.duration().asMonths() gets the length of the duration in months.
Years 1.6.0+
As with the other getters for durations, moment.duration().years() gets the years.
moment.duration().asYears() gets the length of the duration in years.
Add Time 2.1.0+
Mutates the original duration by adding time.
The same keys and shorthands used to create durations can be used here as the second argument.
Note that adding an invalid duration to any other duration results in an invalid duration.
Subtract Time 2.1.0+
Mutates the original duration by subtracting time.
The same keys and shorthands used to create durations can be used here as the second argument.
Note that adding an invalid duration to any other duration results in an invalid duration.
Using Duration with Diff 2.1.0+
You can also use duration with moment#diff to get the duration between two moments. To do so, simply pass the moment#diff method into moment#duration as follows:
As Unit of Time 2.1.0+
Invalid durations return NaN for all units.
Get Unit of Time 2.1.0+
Invalid durations return NaN for all units.
As JSON 2.9.0+
When serializing a duration object to JSON, it will be represented as an ISO8601 string.
Invalid durations return Invalid Date as json representation.
Is a Duration 1.6.0+
As ISO 8601 String 2.8.0+
Returns duration in string as specified by ISO 8601 standard.
Format PnYnMnDTnHnMnS description:
Unit | Meaning |
---|---|
P | _P_ stands for period. Placed at the start of the duration representation. |
Y | Year |
M | Month |
D | Day |
T | Designator that precedes the time components. |
H | Hour |
M | Minute |
S | Second |
Locale 2.17.1+
Suffixes in humanize() are also internationalized:
Utilities
Moment exposes some methods which may be useful to people extending the library or writing custom parsers.
Normalize Units 2.3.0+
Many of Moment’s functions allow the caller to pass in aliases for unit enums. For example, all of the get s below are equivalent.
If you’re extending the library, you may want access to Moment’s facilities for that in order to better align your functionality with Moment’s.
Invalid 2.3.0+
You can create your own invalid Moment objects, which is useful in making your own parser.
invalid also accepts an object which specifies which parsing flags to set. This will not set the userInvalidated parsing flag unless it’s one of the properties specified.
Plugins
Some other people have made plugins for Moment.js that may be useful to you.
Strftime
MSDate
Convert a moment to an OA date:
Or, convert an OA date to a moment :
More information and detailed docs can be found on GitHub at http://markitondemand.github.io/moment-msdate/.
Java DateFormat Parser
If you want to work with the java.text.DateFormat you can use this plugin.
Date Ranges
Documentation can be found on the homepage github.com/rotaready/moment-range.
And it is also available for the web at the repository below.
Full documentation of all the options and features is here.
It’s available on npm like so:
Or just grab the JS file from here.
Precise Range
The Precise Range plugin, written by Rob Dawson, can be used to display exact, human-readable representations of date/time ranges:
To obtain the raw numeric values rather than a string, pass the value true as the third argument to the method:
ISO Calendar
If you are looking for a Python-like isocalendar method, you can use Rocky Meza’s plugin
Calling the isocalendar method on a moment will return an array like the following:
[year, week_of_year, day_of_week, minutes_since_midnight]
You can also reconstruct a moment from a isocalendar array.
Jalaali Calendar
When installed, it will wrap moment and moment will be able to format and parse Jalaali years and months. Here is a short example:
Hijri Calendar
If you want to work with Hijri calendar then you can use moment-hijri plugin. moment-hijri is a moment plugin for the Hijri lunar calendar based on Umm al-Qura calculations. This plugin is developed by Suhail Alkowaileet.
When you install it, it will wrap moment and you will be able to parse Hijri dates. Here is a short example:
Islamic Civil Calendar
This is another Hijri calendar (based on civil calculations).
Recur
This plugin will allow you to create length-based intervals (days, weeks, etc.) and calendar-based intervals (daysOfMonth, monthsOfYear, etc.).
It provides a matches function to test whether a date recurs according to the rules set, as well as generator functions to get the next and previous dates in a series.
The repository, documentation, and many more examples can be found at github.com/c-trimm/moment-recur
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.
Yes, it does smart pluralization.
Not short enough for you?
Fiscal Quarters
If you ever have need for Fiscal, Calendar or Academic quarters, you can use the moment-fquarter plugin by @robgallen.
At its simplest, just call the fquarter method on any moment object. It returns a formatted string with April being the first quarter.
You can pass in any month as the starting quarter, e.g. July
If you want calendar quarters, start in January
Parse Date Format
This plugin extracts the format of a date/time string.
That allows to create smart date inputs that let your users set a Date/Time and lets you extract the user’s preferred format for future usage. Find an example usage of it at minutes.io.
The Plugin has been authored by @gr2m. Links: Demo | Source
Round
This plugin will round date/time to a given interval.
Transform
moment-transform is a plugin that manipulated dates through patterns. You can use basic operations –set/add/subtract– on individual parts (hours, month, …) of a Moment instance.
Optional parameters lets you specify custom patterns and force strict pattern usage (non-alphabetic characters are not mandatory in passed string by default).
You can see it live there while the repository is here.
Taiwan Calendar
When installed, it will wrap moment and moment will be able to format and parse Taiwan years. Here is a short example:
Duration Format
This is a plugin that will allow comprehensive formatting of Moment Durations.
Timer
This is a Moment.js plugin that allows the use of timers, which offer much more control than the native JavaScript timers. It’s basically a rewrite of JavaScripts own setInterval and setTimeout.
Business
This is a Moment.js library that allows Moment operations for Western work weeks: 7 day weeks where Saturday and Sunday are non-work days.
Short Date Formatter
If you want to format times in a short way, you can use the moment-shortformat plugin by @researchgate.
It is based on and similar to the moment.twitter plugin but has a different output.
You can also disable the use of the relative time templates
If the date is too far in the future or the past it will display like that