MomentJS - Getter/Setter
Modern Date/Time: Getters & Setters in Moment.js
Section titled “Modern Date/Time: Getters & Setters in Moment.js”Moment.js provides convenient methods to both retrieve (get) and modify (set) specific units of time within a Moment object (like year, month, hour, etc.).
Mutability Warning: A crucial aspect of Moment.js setters is that they mutate the original Moment object. This can lead to unexpected side effects if not handled carefully. Always consider cloning (.clone()) before modifying if you need to preserve the original moment.
Common Getters and Setters
Section titled “Common Getters and Setters”Most units have corresponding getter and setter methods, often with singular and plural aliases:
| Unit | Getter Syntax | Setter Syntax |
|---|---|---|
| Millisecond | moment().millisecond() or .milliseconds() | moment().millisecond(Number) or .milliseconds(Number) (0-999) |
| Second | moment().second() or .seconds() | moment().second(Number) or .seconds(Number) (0-59) |
| Minute | moment().minute() or .minutes() | moment().minute(Number) or .minutes(Number) (0-59) |
| Hour | moment().hour() or .hours() | moment().hour(Number) or .hours(Number) (0-23) |
| Date of Month | moment().date() or .dates() | moment().date(Number) or .dates(Number) (1-31) |
| Day of Week | moment().day() or .days() (Locale aware, 0=Sun, 6=Sat) | moment().day(Number|String) or .days(Number|String) (0-6 or locale day name) |
| Day of Week (ISO) | moment().isoWeekday() (1=Mon, 7=Sun) | moment().isoWeekday(Number) (1-7) |
| Day of Year | moment().dayOfYear() | moment().dayOfYear(Number) (1-366) |
| Week of Year | moment().week() or .weeks() (Locale aware) | moment().week(Number) or .weeks(Number) |
| Week of Year (ISO) | moment().isoWeek() or .isoWeeks() | moment().isoWeek(Number) or .isoWeeks(Number) |
| Month | moment().month() (0-11, 0=Jan) | moment().month(Number|String) (0-11 or locale month name) |
| Quarter | moment().quarter() or .quarters() (1-4) | moment().quarter(Number) or .quarters(Number) (1-4) |
| Year | moment().year() or .years() | moment().year(Number) or .years(Number) |
| Week Year | moment().weekYear() (Locale aware) | moment().weekYear(Number) |
| ISO Week Year | moment().isoWeekYear() | moment().isoWeekYear(Number) |
| Weeks in Year | moment().weeksInYear() (Locale aware) | N/A |
| ISO Weeks in Year | moment().isoWeeksInYear() | N/A |
Generic Get/Set Methods
Section titled “Generic Get/Set Methods”Moment.js also provides generic get and set methods:
moment().get(String): Retrieves a unit value using a string key (e.g.,moment().get('year'),moment().get('month')). Note: ‘month’ is 0-indexed.moment().set(String, Int): Sets a single unit using a string key (e.g.,moment().set('hour', 13)).moment().set(Object): Sets multiple units at once using an object (e.g.,moment().set({ year: 2024, month: 0, date: 1 })). Remember month is 0-indexed here too!
Example: Using Getters and Setters (with Cloning)
Section titled “Example: Using Getters and Setters (with Cloning)”const now = moment();console.log('Original:', now.format('YYYY-MM-DD HH:mm:ss'));
// Get the current hourconst currentHour = now.hour();console.log('Current Hour:', currentHour);
// --- Mutating Example (Use with care!) ---// const modifiedDirectly = now.year(2025);// console.log('Original (MUTATED!):', now.format('YYYY-MM-DD HH:mm:ss'));// console.log('Modified Directly:', modifiedDirectly.format('YYYY-MM-DD HH:mm:ss'));
// --- Safer Example using clone() ---const safeModified = now.clone().year(2025).month(0); // Set year to 2025, month to January
console.log('Original (Safe):', now.format('YYYY-MM-DD HH:mm:ss')); // Unchangedconsole.log('Safely Modified:', safeModified.format('YYYY-MM-DD HH:mm:ss'));
// Using generic setconst startOfDay = moment().clone().set({ hour: 0, minute: 0, second: 0, millisecond: 0 });console.log('Start of Today:', startOfDay.format('YYYY-MM-DD HH:mm:ss.SSS'));Finding Maximum/Minimum Moments
Section titled “Finding Maximum/Minimum Moments”Moment.js can easily find the earliest or latest moment from a list:
moment.max(Moment[, Moment...])ormoment.max(Moment[]): Returns the latest Moment object from the provided arguments or array.moment.min(Moment[, Moment...])ormoment.min(Moment[]): Returns the earliest Moment object.
const date1 = moment('2023-10-26');const date2 = moment('2023-11-15');const date3 = moment('2023-10-01');
const latestDate = moment.max(date1, date2, date3);const earliestDate = moment.min([date1, date2, date3]);
console.log('Latest:', latestDate.format('YYYY-MM-DD')); // Output: Latest: 2023-11-15console.log('Earliest:', earliestDate.format('YYYY-MM-DD')); // Output: Earliest: 2023-10-01Getters and setters are fundamental for interacting with Moment objects, but always be mindful of mutability when using setters.
See the docs for more details: https://momentjs.com/docs/#/get-set/