### Install Moment.js on Windows Source: https://github.com/moment/momentjs.com/blob/master/readme.md Run this PowerShell script to install Moment.js on Windows. Ensure PowerShell and npm are installed beforehand. ```powershell ./compile.ps1 ``` -------------------------------- ### Install Moment.js with npm Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/01-node-js.md Use npm to install the Moment.js library before requiring it in your project. ```bash npm install moment ``` -------------------------------- ### Install Moment.js on Linux/UNIX Source: https://github.com/moment/momentjs.com/blob/master/readme.md Execute this script to compile and install Moment.js on Linux or UNIX-based systems. ```bash ./compile.sh ``` -------------------------------- ### Install Moment.js with Bower Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/03-bower.md Use this command to install Moment.js and save it as a dependency in your project's bower.json file. ```bash bower install --save moment ``` -------------------------------- ### Installing Twix via npm Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/05-twix.md Shows the command to install the Twix library using npm. This is the recommended method for project integration. ```bash npm install twix ``` -------------------------------- ### Install moment-islamic-civil Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/10-islamic-civil.md Install the moment-islamic-civil plugin using npm. This plugin provides an alternative Hijri calendar implementation. ```bash npm install moment-islamic-civil ``` -------------------------------- ### Moment.js Get Method Usage Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/19-get.md Demonstrates the general usage of the get() method with various units. Units are case-insensitive and support plural and short forms. ```javascript moment().get('year'); moment().get('month'); // 0 to 11 moment().get('date'); moment().get('hour'); moment().get('minute'); moment().get('second'); moment().get('millisecond'); ``` ```javascript moment().get(unit) === moment()[unit]() ``` -------------------------------- ### Equivalent 'get' operations with unit aliases Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/09-utilities/01-normalize-units.md Demonstrates how different string aliases for the 'year' unit all yield the same result when used with the `get` method. ```javascript var m = moment(); m.get('y'); m.get('year'); m.get('years'); ``` -------------------------------- ### Get and Set Relative Time Rounding Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/07-customization/14-relative-time-rounding.md Demonstrates how to get the current relative time rounding function and set a new one, such as `Math.floor` for rounding down. It also shows setting relative time thresholds and reverting to the default rounding. ```javascript var roundingDefault = moment.relativeTimeRounding(); // Round relative time evaluation down moment.relativeTimeRounding(Math.floor); moment.relativeTimeThreshold('s', 60); moment.relativeTimeThreshold('m', 60); moment.relativeTimeThreshold('h', 24); moment.relativeTimeThreshold('d', 7); moment.relativeTimeThreshold('w', 4); moment.relativeTimeThreshold('M', 12); var a = moment(); a.subtract({hours: 23, minutes: 59, seconds: 59}); a.toNow(); // == 'in 23 hours' 'Round down towards the nearest hour' // back to default moment.relativeTimeRounding(roundingDefault); ``` -------------------------------- ### Packed Time Zone Data Example Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/03-data-formats/02-packed-format.md An example of a time zone's data represented in the packed format. This format is a single string containing six pipe-separated sections. ```javascript 'America/Los_Angeles|PST PDT|80 70|01010101010|1Lzm0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|15e6' ``` -------------------------------- ### Locale Fallback Order Example Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/01-changing-locale.md When a locale is not found, Moment.js tries a sequence of fallbacks. This example shows the order in which locales are attempted if the initial locale 'AA-BB' is not available. ```text "AA-BB", "AA-CC", "AA", "XX-YY", "XX" ``` -------------------------------- ### Forgiving vs. Strict Parsing Example Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/01-parsing/03-string-format.md Demonstrates Moment.js's forgiving parsing behavior where extra text in the input string might be ignored. This example highlights a potential pitfall. ```javascript moment('2016 is a date', 'YYYY-MM-DD').isValid() //true, 2016 was matched ``` -------------------------------- ### Custom Starting Month for Fiscal Quarter Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/13-fquarter.md Pass a month number (1-12) to the fquarter method to define the starting month of the fiscal year. This example sets July (month 7) as the start of the quarter. ```javascript moment("2013-01-01").fquarter(7); // Q3 2012/13 ``` -------------------------------- ### Get ISO Week Year Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/16-iso-week-year.md Retrieves the ISO week-year for the current moment. No setup is required beyond initializing a moment object. ```javascript moment().isoWeekYear(); ``` -------------------------------- ### Calculate Precise Date/Time Difference Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/06-preciserange.md Use the `preciseDiff` method to get a human-readable string representing the difference between two moments. Ensure the moment-precise-range-plugin is installed. ```javascript moment("2014-01-01 12:00:00").preciseDiff("2015-03-04 16:05:06"); // 1 year 2 months 3 days 4 hours 5 minutes 6 seconds ``` -------------------------------- ### Moment.js startOf Examples Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/03-start-of.md Demonstrates various uses of the `startOf` method to set a moment to the beginning of different time units. ```javascript 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('quarter'); // set to the beginning of the current quarter, 1st day of months, 12:00 am moment().startOf('week'); // set to the first day of this week, 12:00 am moment().startOf('isoWeek'); // set to the first day of this week according to ISO 8601, 12:00 am moment().startOf('day'); // set to 12:00 am today moment().startOf('date'); // 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); ``` -------------------------------- ### Calendar Quarters Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/13-fquarter.md To display standard calendar quarters, pass 1 (for January) as the starting month to the fquarter method. This example shows the first calendar quarter for January 1st, 2013. ```javascript moment("2013-01-01").fquarter(1); // Q1 2013 ``` -------------------------------- ### Run Moment.js Locally Source: https://github.com/moment/momentjs.com/blob/master/readme.md Use this Grunt command to start a local development server. If you encounter issues with the default localhost address, switch to 'localhost'. ```bash grunt server ``` -------------------------------- ### Filter, Link, and Pack Timezone Data Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/05-data-utilities/07-filter-link-pack.md Use moment.tz.filterLinkPack to compress timezone data. Pass an unpacked bundle, start year, and end year to get a filtered, linked, and packed bundle. ```javascript moment.tz.filterLinkPack(UnpackedBundle, Number, Number); ``` -------------------------------- ### Default Fiscal Quarter Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/13-fquarter.md Use the fquarter method with no arguments to get the default fiscal quarter, assuming April as the first month of the quarter. This example shows the quarter for January 1st, 2013. ```javascript moment("2013-01-01").fquarter(); // Q4 2012/13 ``` -------------------------------- ### Get a specific locale-specific weekday Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/07-listing-months-weekdays.md Retrieve a specific weekday name based on locale-specific ordering by passing `true` and the desired index to `moment.weekdays()`. For example, index 2 in Arabic locale will return Monday. ```javascript moment.weekdays(true, 2); //will result in Monday in Arabic ``` -------------------------------- ### Basic Usage of moment#from Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/04-displaying/03-from.md Demonstrates the basic usage of the moment#from method to display the difference between two moments. ```javascript var a = moment([2007, 0, 28]); var b = moment([2007, 0, 29]); a.from(b) // "a day ago" ``` -------------------------------- ### Using Twix to Format Date Ranges Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/05-twix.md Demonstrates how to create and format a date range using the Twix plugin. Ensure Twix is installed and imported before use. ```javascript 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' ``` -------------------------------- ### Get Quarter Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/13-quarter.md Gets the quarter of the year (1 to 4) for a given Moment.js object. ```APIDOC ## Get Quarter ### Description Gets the quarter (1 to 4) of a Moment.js date. ### Method `moment().quarter()` ### Parameters None ### Response - **quarter** (Number) - The quarter of the year (1, 2, 3, or 4). ### Example ```javascript moment('2013-01-01T00:00:00.000').quarter() // Returns 1 ``` ``` -------------------------------- ### Basic Moment.js Formatting Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/04-displaying/01-format.md Demonstrates various ways to format a Moment.js date object using different token combinations. Includes examples for full date-time, abbreviated formats, and handling invalid dates. ```javascript moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds) moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm" moment().format("ddd, hA"); // "Sun, 3PM" moment().format("[Today is] dddd"); // "Today is Sunday" moment('gibberish').format('YYYY MM DD'); // "Invalid date" ``` -------------------------------- ### Setting and Using Instance Locales Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/02-instance-locale.md Demonstrates how to set a locale for a specific Moment.js instance, affecting its formatting, and how global locale changes do not impact already set instances. Also shows how to reset an instance's locale. ```javascript moment.locale('en'); // default the locale to English var localLocale = moment(); localLocale.locale('fr'); // set this instance to use French localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01 moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM moment.locale('es'); // change the global locale to Spanish localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01 moment().format('LLLL'); // Domingo 15 Julio 2012 11:01 localLocale.locale(['tq', 'fr']); // set this instance to the first localization found localLocale.format('LLLL'); // dimanche 15 juillet 2012 11:01 moment().format('LLLL'); // Sunday, July 15 2012 11:01 AM localLocale.locale(false); // reset the instance locale localLocale.format('LLLL'); // Domingo 15 Julio 2012 11:01 moment().format('LLLL'); // Domingo 15 Julio 2012 11:01 ``` -------------------------------- ### Get Total Duration in Hours Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/07-hours.md Use `.asHours()` to get the entire duration expressed in hours. ```javascript moment.duration().asHours(); ``` -------------------------------- ### Import Moment.js as a Module with System.js Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/10-system-js.md Configure System.js to set the base URL and then import Moment.js as a module. This is the standard way to load Moment.js when using System.js. ```javascript ``` -------------------------------- ### Get Minutes (0-59) Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/06-minutes.md Use `.minutes()` to get the minutes component of a duration, which will be a value between 0 and 59. ```javascript moment.duration().minutes(); ``` -------------------------------- ### Moment.js startOf('hour') Equivalent Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/03-start-of.md Shows the manual manipulation equivalent to `moment().startOf('hour')`. ```javascript moment().startOf('hour'); moment().minutes(0).seconds(0).milliseconds(0) ``` -------------------------------- ### Configure Moment.js Package with Require.js Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/04-require-js.md Set up Require.js to recognize Moment.js as a package. Specify the location relative to your baseUrl, such as 'bower_components/moment' or 'node_modules/moment'. ```javascript requirejs.config({ packages: [{ name: 'moment', // This location is relative to baseUrl. Choose bower_components // or node_modules, depending on how moment was installed. location: '[bower_components|node_modules]/moment', main: 'moment' }] }); ``` -------------------------------- ### Get Years as Integer Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/11-years.md Use `years()` to get the whole number of years in a duration. This is useful for discrete year counts. ```javascript moment.duration().years(); ``` -------------------------------- ### Require Moment.js and Locales with Require.js Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/04-require-js.md Demonstrates various ways to load Moment.js and its locales using Require.js's define function. Includes loading only the core, core with a specific locale, all locales, and asynchronously loading a locale. ```javascript // only needing core define(['moment'], function (moment) { console.log(moment().format('LLLL')); // 'Friday, June 24, 2016 1:42 AM' }); // core with single locale define(['moment', 'moment/locale/de'], function (moment) { moment.locale('de'); console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42' }); // core with all locales define(['moment/min/moment-with-locales'], function (moment) { moment.locale('de'); console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42' }); // async load locale define(['require', 'moment'], function(require, moment) { // Inside some module after the locale is detected. This is the // case where the locale is not known before module load time. require(['moment/locale/de'], function(localeModule) { // here the locale is loaded, but not yet in use console.log(moment().format('LLLL')); // 'Friday, June 24, 2016 1:42 AM' moment.locale('de'); // Use moment now that the locale has been properly set. console.log(moment().format('LLLL')); // 'Freitag, 24. Juni 2016 01:42' }) }); ``` -------------------------------- ### Configure Require.js Paths Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/00-use-it/03-require-js.md Configure Require.js to map the 'moment' alias to the correct path for the moment-timezone library, including its data. ```javascript require.config({ paths: { "moment": "path/to/moment-timezone-with-data" } }); ``` -------------------------------- ### Get Total Duration in Seconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/05-seconds.md Use `moment.duration().asSeconds()` to get the total length of the duration expressed in seconds. This can be a floating-point number. ```javascript moment.duration(500).asSeconds(); // 0.5 moment.duration(1500).asSeconds(); // 1.5 moment.duration(15000).asSeconds(); // 15 ``` -------------------------------- ### Get Total Duration in Months Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/10-months.md Use `asMonths()` to get the total length of the duration expressed in months, including fractional parts. ```javascript moment.duration().asMonths(); ``` -------------------------------- ### Get and Set Weekday with Locale Awareness Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/07-weekday.md Demonstrates setting the weekday to values outside the standard 0-6 range, showing how it correctly calculates the previous or next occurrence based on the locale's first day of the week. ```javascript // when Monday is the first day of the week moment().weekday(-7); // last Monday moment().weekday(7); // next Monday // when Sunday is the first day of the week moment().weekday(-7); // last Sunday moment().weekday(7); // next Sunday ``` -------------------------------- ### Switching from UTC to Local Time Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/01-parsing/13-utc.md Illustrates how to convert a moment created in UTC mode to local time using the .local() method. ```javascript var a = moment.utc([2011, 0, 1, 8]); a.hours(); // 8 UTC a.local(); a.hours(); // 0 PST ``` -------------------------------- ### Get Seconds Part of a Duration Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/05-seconds.md Use `moment.duration().seconds()` to get the seconds component of a duration. This value will always be between 0 and 59. ```javascript moment.duration(500).seconds(); // 0 moment.duration(1500).seconds(); // 1 moment.duration(15000).seconds(); // 15 ``` -------------------------------- ### Date Math vs Time Math with DST Source: https://github.com/moment/momentjs.com/blob/master/guides/moment/00-lib-concepts/02-date-time-math.md Illustrates how adding one day (date math) differs from adding 24 hours (time math) due to daylight saving time transitions. ```javascript //date math moment('2016-03-12 13:00:00').add(1, 'day').format('LLL') "March 13, 2016 1:00 PM" //time math moment('2016-03-12 13:00:00').add(24, 'hours').format('LLL') "March 13, 2016 2:00 PM" ``` -------------------------------- ### Get Total Duration in Minutes Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/06-minutes.md Use `.asMinutes()` to get the total length of the duration expressed in minutes, including hours and days. ```javascript moment.duration().asMinutes(); ``` -------------------------------- ### Get Months (0-11) from Duration Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/10-months.md Use `months()` to get the number of full months within the duration, ranging from 0 to 11. ```javascript moment.duration().months(); ``` -------------------------------- ### Adding Zone Data and Creating Links Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/03-data-formats/03-link-format.md Demonstrates how to add custom timezone data and establish links between zones that share identical data. This is useful for reducing data duplication. Ensure the 'moment-timezone' library is included. ```javascript moment.tz.add('America/Los_Angeles|PST PDT|80 70|01010101010|1Lzm0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0'); moment.tz.link('America/Los_Angeles|US/Pacific'); moment.tz("2013-12-01", "America/Los_Angeles").format(); // 2013-12-01T00:00:00-08:00 moment.tz("2013-12-01", "US/Pacific").format(); // 2013-12-01T00:00:00-08:00 ``` -------------------------------- ### Get Milliseconds Part of a Duration Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/04-milliseconds.md Use `moment.duration().milliseconds()` to get the milliseconds component of a duration. This value will always be between 0 and 999. ```javascript moment.duration(500).milliseconds(); // 500 moment.duration(1500).milliseconds(); // 500 moment.duration(15000).milliseconds(); // 0 ``` -------------------------------- ### Equality Check by Month and Day Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/05-query/02-is-same.md Demonstrates how specifying 'month' or 'day' as the granularity affects the comparison. 'month' checks year and month, while 'day' checks year, month, and day. ```javascript moment('2010-01-01').isSame('2011-01-01', 'month'); // false, different year moment('2010-01-01').isSame('2010-02-01', 'day'); // false, different month ``` -------------------------------- ### Time Zone Conversion Affects Start of Day Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/01-using-timezones/03-converting-to-zone.md Demonstrates how changing the time zone with `tz()` affects the calculation of the start of the day. ```javascript var m = moment.tz("2013-11-18 11:55", "America/Toronto"); m.format(); // 2013-11-18T11:55:00-05:00 m.startOf("day").format(); // 2013-11-18T00:00:00-05:00 m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00 m.startOf("day").format(); // 2013-11-18T00:00:00+01:00 ``` -------------------------------- ### Comparing zone() and utcOffset() for Getting Offset Source: https://github.com/moment/momentjs.com/blob/master/guides/moment/02-warnings/07-zone.md Demonstrates the difference in output between the deprecated `zone()` method and the recommended `utcOffset()` method when retrieving the offset in minutes from UTC. Note the inverted sign convention of `zone()`. ```js moment().zone() 360 //is replaced by moment().utcOffset() -360 ``` -------------------------------- ### Get Years as Floating-Point Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/11-years.md Use `asYears()` to get the total duration expressed in years, including fractional parts. This is useful for precise calculations. ```javascript moment.duration().asYears(); ``` -------------------------------- ### Rounding and Ceil/Floor Operations Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/15-round.md Demonstrates how to use the round, ceil, and floor methods provided by the moment-round plugin to adjust date/time values to specific intervals. Ensure the plugin is required before use. ```javascript require('moment-round'); var m = new moment(); // 2015-06-18 15:30:19 m.round(5, 'seconds'); // 2015-06-18 15:30:20 m.ceil(3, 'minutes'); // 2015-06-18 15:33:00 m.floor(16, 'hours'); // 2015-06-18 00:00:00 m.ceil(21, 'hours'); // 2015-06-18 21:00:00 m.ceil(20, 'hours'); // 2015-06-19 00:00:00 ``` -------------------------------- ### Get Current Date and Time Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/01-parsing/01-now.md Call `moment()` with no parameters to get the current date and time. This is equivalent to calling `moment(new Date())`. ```javascript var now = moment(); ``` -------------------------------- ### Moment.js startOf('year') Equivalent Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/03-start-of.md Shows the manual manipulation equivalent to `moment().startOf('year')`. ```javascript moment().startOf('year'); moment().month(0).date(1).hours(0).minutes(0).seconds(0).milliseconds(0); ``` -------------------------------- ### Creating Durations Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/01-creating.md Demonstrates the different methods for creating duration objects in Moment.js. ```APIDOC ## Creating Durations This section details how to instantiate `moment.duration()` objects using various input types. ### Method Signatures - `moment.duration(milliseconds: Number)` - `moment.duration(Object)` - `moment.duration(String)` - `moment.duration(Number, String)` - `moment.duration(String, String)` (from v2.25.0) ### Examples #### Using milliseconds: ```javascript moment.duration(100); ``` #### Using a number and a unit of measurement: ```javascript 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'); // From v2.25.0 moment.duration('2', 'years'); ``` #### Using an object with multiple units: ```javascript moment.duration({ seconds: 2, minutes: 2, hours: 2, days: 2, weeks: 2, months: '2', years: '2' }); ``` #### Parsing ASP.NET style time spans (from v2.1.0): Formats: `HH:mm:ss`, `HH:mm:ss.fff`, `d.HH:mm:ss.fff`, `HH:mm` (from v2.3.0) ```javascript moment.duration('23:59:59'); moment.duration('23:59:59.999'); moment.duration('7.23:59:59.999'); moment.duration('23:59'); ``` #### Parsing ISO 8601 durations (from v2.3.0): ```javascript moment.duration('P1Y2M3DT4H5M6S'); moment.duration('P1M'); ``` #### Parsing durations with space between days and time (from v2.11.0): ```javascript moment.duration('7 23:59:59.999'); ``` #### Parsing durations with mixed signs (from v2.13.0): ```javascript moment.duration('PT-6H3M'); ``` #### Creating invalid durations (from v2.18.0): ```javascript moment.duration(NaN); moment.duration(NaN, 'days'); moment.duration.invalid(); ``` ### Supported Units Shorthand | Key | Shorthand | |--------------|-----------| | years | y | | months | M | | weeks | w | | days | d | | hours | h | | minutes | m | | seconds | s | | milliseconds | ms | ``` -------------------------------- ### Get Duration in Different Units Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/15-as.md Use Duration#as('x') to get the duration in hours, minutes, seconds, or milliseconds. All shorthand keys from moment#add are applicable. ```javascript duration.as('hours'); duration.as('minutes'); duration.as('seconds'); duration.as('milliseconds'); ``` -------------------------------- ### Configure System.js to Load Moment.js as Global Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/10-system-js.md Use System.js meta configuration to load Moment.js as a global variable. This is useful if your application or libraries expect Moment to be available on the window object. ```javascript System.config({ meta: { 'moment': { format: 'global' } } }); ``` -------------------------------- ### Setting Individual Date and Time Units Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/20-set.md Demonstrates setting individual date and time components using the set method with string unit names and integer values. ```javascript moment().set('year', 2013); moment().set('month', 3); // April moment().set('date', 1); moment().set('hour', 13); moment().set('minute', 20); moment().set('second', 30); moment().set('millisecond', 123); ``` -------------------------------- ### Get Total Duration in Milliseconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/04-milliseconds.md Use `moment.duration().asMilliseconds()` to get the total length of a duration expressed in milliseconds. This represents the full duration, not just the milliseconds part. ```javascript moment.duration(500).asMilliseconds(); // 500 moment.duration(1500).asMilliseconds(); // 1500 moment.duration(15000).asMilliseconds(); // 15000 ``` -------------------------------- ### Import and Use moment-business Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/20-moment-business.md Import the moment-business plugin and use its functions to check for weekdays and add business days. ```javascript import business from 'moment-business'; // true if the moment is Mon-Fri, false otherwise business.isWeekDay(someMoment); // Adds five work days to the Moment business.addWeekDays(someMoment, 5); ``` -------------------------------- ### Get Time Zone Names for a Country Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/01-using-timezones/08-getting-country-zones.md Use `moment.tz.zonesForCountry()` with a two-letter ISO 3166-1 country code to get an alphabetically sorted array of time zone names. ```javascript moment.tz.zonesForCountry('US'); ``` ```javascript [ "America/Adak", "America/Anchorage", ... "Pacific/Honolulu" ] ``` -------------------------------- ### Get Milliseconds Since Epoch with valueOf() Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/04-displaying/08-unix-timestamp-milliseconds.md Use the `valueOf()` method on a Moment object to get the number of milliseconds since the Unix Epoch. This is equivalent to `Date#valueOf()`. ```javascript moment(1318874398806).valueOf(); // 1318874398806 ``` -------------------------------- ### Import and Use Moment.js Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/08-webpack.md Import Moment.js in your JavaScript file and use its basic formatting functionality. This is a standard way to include and use Moment.js in a project. ```javascript var moment = require('moment'); moment().format(); ``` -------------------------------- ### Format a Moment Duration Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/18-duration-format.md Demonstrates basic formatting of a Moment Duration object into an 'hours:minutes' string format. Ensure the moment-duration-format plugin is installed and imported. ```javascript moment.duration(123, "minutes").format("h:mm"); // "2:03" ``` -------------------------------- ### Get Unix Timestamp in Seconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/04-displaying/09-unix-timestamp.md Use the `.unix()` method to get the number of seconds since the Unix Epoch. This value is floored to the nearest second and does not include milliseconds. ```javascript moment(1318874398806).unix(); // 1318874398 ``` -------------------------------- ### Moment.js Getters and Setters Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/00-intro.md Demonstrates using Moment.js getters and setters to get and set seconds, comparing with native Date object behavior. ```javascript moment().seconds(30).valueOf() === new Date().setSeconds(30); moment().seconds() === new Date().getSeconds(); ``` -------------------------------- ### Get Time Zone Abbreviation Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/02-zone-object/02-abbr.md Use the `abbr` method on a Zone object to get the abbreviation for a given timestamp in milliseconds. This is useful for displaying time zone information concisely. ```javascript moment.tz.zone('America/Los_Angeles').abbr(1403465838805); // PDT moment.tz.zone('America/Los_Angeles').abbr(1388563200000); // PST ``` -------------------------------- ### Comparing zone(number) and utcOffset(number) for Setting Offset Source: https://github.com/moment/momentjs.com/blob/master/guides/moment/02-warnings/07-zone.md Illustrates how to set the UTC offset using the deprecated `zone(number)` method versus the recommended `utcOffset(number)` method. The sign convention is inverted between the two. ```js moment().zone(420) //is replaced by moment().utcOffset(-420) ``` -------------------------------- ### Get Units of Time from Duration Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/16-get.md Use Duration#get() with shorthand keys to retrieve hours, minutes, seconds, and milliseconds from a duration object. Invalid durations return NaN. ```javascript duration.get('hours'); duration.get('minutes'); duration.get('seconds'); duration.get('milliseconds'); ``` -------------------------------- ### Import Moment.js and Locale Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/09-typescript.md Import Moment.js and a specific locale file (e.g., 'pt-br') to enable locale-specific formatting. Demonstrates how to set and check the current locale. ```javascript import * as moment from 'moment'; import 'moment/locale/pt-br'; console.log(moment.locale()); // en moment.locale('fr'); console.log(moment.locale()); // fr moment.locale('pt-br'); console.log(moment.locale()); // pt-br ``` -------------------------------- ### Method Chaining for Moment Manipulation Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/00-intro.md Demonstrates the fluent interface pattern for chaining multiple manipulation methods on a Moment object. Note that moments are mutable and will be changed by these operations. ```javascript moment().add(7, 'days').subtract(1, 'months').year(2009).hours(0).minutes(0).seconds(0); ``` -------------------------------- ### Decimal Year and Quarter Math in Moment.js Source: https://github.com/moment/momentjs.com/blob/master/guides/moment/00-lib-concepts/02-date-time-math.md Explains how decimal values for 'years' and 'quarters' are converted to months and then rounded to the nearest whole number. ```javascript moment().add(1.5, 'years') == moment().add(18, 'months') moment().add(.8, 'years') == moment().add(9.6, 'months') == moment().add(10, 'months') moment().add(1.5, 'quarters') == moment().add(4.5, 'months') == moment().add(5, 'months') ``` -------------------------------- ### Accessing Instance Locale Data Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/02-instance-locale.md Shows how to retrieve the locale configuration for a Moment.js instance and use it to access locale-specific data, such as month names. It also demonstrates switching the instance's locale and accessing data from the new locale. ```javascript var fr = moment().locale('fr'); fr.localeData().months(moment([2012, 0])) // "janvier" fr.locale('en'); fr.localeData().months(moment([2012, 0])) // "January" ``` -------------------------------- ### Get or Set ISO Week of Year Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/11-iso-week.md The `isoWeek()` method can be used to get or set the ISO week of the year. When setting the week, the day of the week is retained. The `isoWeeks()` method is an alias for `isoWeek()`. ```APIDOC ## moment().isoWeek() ### Description Gets the ISO week of the year. ### Method GET ### Endpoint N/A (SDK method) ### Parameters None ### Response #### Success Response - **week** (Number) - The ISO week number of the year. ## moment().isoWeek(Number) ### Description Sets the ISO week of the year. When setting the week of the year, the day of the week is retained. ### Method SET ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **Number** (Number) - Required - The ISO week number to set. ### Response #### Success Response - **moment** (Object) - The moment object with the updated ISO week. ## moment().isoWeeks() ### Description Alias for `moment().isoWeek()`. Gets the ISO week of the year. ### Method GET ### Endpoint N/A (SDK method) ### Parameters None ### Response #### Success Response - **week** (Number) - The ISO week number of the year. ## moment().isoWeeks(Number) ### Description Alias for `moment().isoWeek(Number)`. Sets the ISO week of the year. ### Method SET ### Endpoint N/A (SDK method) ### Parameters #### Path Parameters - **Number** (Number) - Required - The ISO week number to set. ### Response #### Success Response - **moment** (Object) - The moment object with the updated ISO week. ``` -------------------------------- ### Get or Set Milliseconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/01-millisecond.md This demonstrates how to get the current milliseconds from a Moment.js object or set a new millisecond value. The value should be between 0 and 999. Exceeding this range will cause the milliseconds to bubble up to the seconds. ```APIDOC ## Get or Set Milliseconds ### Description Retrieves or sets the milliseconds of a Moment.js object. Accepts numbers from 0 to 999. If the range is exceeded, it will bubble up to the seconds. ### Method Signature `moment().millisecond(Number);` `moment().millisecond(); // Returns Number` `moment().milliseconds(Number);` `moment().milliseconds(); // Returns Number` ### Parameters #### Set Milliseconds - **millisecond** (Number) - Required - The number of milliseconds to set (0-999). #### Get Milliseconds This method takes no parameters when used for getting the milliseconds. ### Examples #### Setting Milliseconds ```javascript // Setting milliseconds to 500 const mom = moment(); mom.millisecond(500); console.log(mom.millisecond()); // Output: 500 // Setting milliseconds to 1500 (will bubble up to seconds) mom.millisecond(1500); console.log(mom.millisecond()); // Output: 500 console.log(mom.second()); // Output: (previous seconds + 1) ``` #### Getting Milliseconds ```javascript const mom = moment(); console.log(mom.millisecond()); // Output: The current milliseconds (0-999) ``` ``` -------------------------------- ### moment.to() with Various Input Types Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/04-displaying/05-to.md Demonstrates the flexibility of the `to()` method by accepting different types of input for comparison, including arrays, Date objects, and strings. ```javascript var a = moment([2007, 0, 28]); var b = moment([2007, 0, 29]); a.to(b); // "in a day" a.to([2007, 0, 29]); // "in a day" a.to(new Date(2007, 0, 29)); // "in a day" a.to("2007-01-29"); // "in a day" ``` -------------------------------- ### Get locale-specific weekdays in order Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/06-i18n/07-listing-months-weekdays.md Use `moment.weekdays(true)` to get an array of weekday names ordered according to the current locale's definition of the first day of the week. This is crucial for accurate display in different cultural contexts. ```javascript moment.locale('ar'); moment.weekdays(true); // lists weekdays Saturday-Friday in Arabic ``` -------------------------------- ### Basic Short Date Formatting Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/21-shortformat.md Format dates in a short way using the moment-shortformat plugin. This example shows formatting for past and future times. ```javascript moment().subtract(5, 'hours').short(); // 5h ago moment().add(5, 'hours').short(); // in 5h ``` -------------------------------- ### asMilliseconds() Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/08-durations/04-milliseconds.md Get the total length of the duration in milliseconds. ```APIDOC ## asMilliseconds() ### Description Get the total length of the duration in milliseconds. ### Method `moment.duration().asMilliseconds()` ### Parameters None ### Request Example ```javascript moment.duration(500).asMilliseconds(); // 500 moment.duration(1500).asMilliseconds(); // 1500 moment.duration(15000).asMilliseconds(); // 15000 ``` ### Response #### Success Response - **milliseconds** (number) - The total duration in milliseconds. ``` -------------------------------- ### Importing Moment Timezone Bundles Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/00-use-it/01-node-js.md Load pre-built bundles of moment-timezone that include a specific range of data. Use the appropriate bundle file for your needs. ```javascript import moment from 'moment-timezone/builds/moment-timezone-with-data-10-year-range.js'; // or .min.js ``` -------------------------------- ### moment().year() Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/14-year.md Gets the year from a Moment.js object. ```APIDOC ## moment().year() ### Description Gets the year from a Moment.js object. ### Method `year()` ### Parameters This method does not accept any parameters. ### Request Example ```javascript const currentYear = moment().year(); ``` ### Response #### Success Response (200) - **Number** (Number) - The current year of the Moment.js object. #### Response Example ```javascript 2023 ``` ``` -------------------------------- ### Clamping a Moment within a Range using min() and max() Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/03-manipulating/06-min.md Demonstrates how to use moment.min() and moment.max() together to ensure a moment object falls within a specific start and end range. This is useful for enforcing boundaries on dates. ```javascript var start = moment().startOf('week'); var end = moment().endOf('week'); var actual = moment().min(start).max(end); ``` -------------------------------- ### Get the Year Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/14-year.md Retrieves the year from a Moment.js object. ```javascript moment().year(); ``` -------------------------------- ### Basic Date Transformations Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/16-transform.md Use basic operations like set/add/subtract on individual date parts using predefined patterns. Examples show transforming to midnight, a specific time, and a date in the past. ```javascript moment().transform('YYYY-MM-+01 00:00:00.000'); // Tonight at midnight moment().transform('14:30:00.000'); // Today, 2:30 pm moment().transform('YYYY-MM--30 00:00:00.000'); // 30 days ago ``` -------------------------------- ### moment().date() Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/05-date.md Gets the day of the month from a Moment.js object. ```APIDOC ## moment().date() ### Description Gets the day of the month from a Moment.js object. ### Method `date()` ### Parameters None ### Request Example ```javascript moment().date(); ``` ### Response #### Success Response (200) - **date** (Number) - The day of the month (1-31). #### Response Example ```javascript 15 ``` ``` -------------------------------- ### Configure Webpack with moment-timezone-data-webpack-plugin Source: https://github.com/moment/momentjs.com/blob/master/docs/moment-timezone/00-use-it/04-webpack.md Shows how to configure the webpack.config.js file to use the moment-timezone-data-webpack-plugin for optimizing the bundled data. This plugin helps reduce the final bundle size by including only necessary zone or year data. ```javascript // webpack.config.js const MomentTimezoneDataPlugin = require('moment-timezone-data-webpack-plugin'); const currentYear = new Date().getFullYear(); module.exports = { plugins: [ // To include only specific zones, use the matchZones option new MomentTimezoneDataPlugin({ matchZones: /^America/ }), // To keep all zones but limit data to specific years, use the year range options new MomentTimezoneDataPlugin({ startYear: currentYear - 5, endYear: currentYear + 5, }), ], }; ``` -------------------------------- ### Get Seconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/02-second.md Retrieves the seconds value from a Moment.js object. ```javascript moment().second(); ``` -------------------------------- ### Including All Locales with Browserify Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/00-use-it/07-browserify.md Include all Moment.js locales for use with Browserify. ```javascript var moment = require('moment'); require("moment/min/locales.min"); moment.locale('cs'); console.log(moment.locale()); // cs ``` -------------------------------- ### Get Milliseconds Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/02-get-set/01-millisecond.md Retrieves the millisecond value from a Moment.js object. ```javascript moment().millisecond(); ``` -------------------------------- ### Moment-Recur Plugin Usage Source: https://github.com/moment/momentjs.com/blob/master/docs/moment/10-plugins/11-recur.md Demonstrates creating length-based and calendar-based intervals, checking matches, generating next/previous occurrences, and modifying rules using the moment-recur plugin. ```javascript var interval = moment( "01/01/2014" ).recur().every(2).days(); // Length Interval interval.matches( "01/03/2014" ); // true interval.next( 2, "L" ); // ["01/03/2014", "01/05/2014"] interval.forget( "days" ); // Remove a rule interval.dayOfMonth( 10 ); // Calendar Interval interval.matches( "05/10/2014" ); // true interval.previous( 2, "L" ); // ["12/10/2013", "11/10/2013"] ```