Skip to content

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.

Most units have corresponding getter and setter methods, often with singular and plural aliases:

UnitGetter SyntaxSetter Syntax
Millisecondmoment().millisecond() or .milliseconds()moment().millisecond(Number) or .milliseconds(Number) (0-999)
Secondmoment().second() or .seconds()moment().second(Number) or .seconds(Number) (0-59)
Minutemoment().minute() or .minutes()moment().minute(Number) or .minutes(Number) (0-59)
Hourmoment().hour() or .hours()moment().hour(Number) or .hours(Number) (0-23)
Date of Monthmoment().date() or .dates()moment().date(Number) or .dates(Number) (1-31)
Day of Weekmoment().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 Yearmoment().dayOfYear()moment().dayOfYear(Number) (1-366)
Week of Yearmoment().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)
Monthmoment().month() (0-11, 0=Jan)moment().month(Number|String) (0-11 or locale month name)
Quartermoment().quarter() or .quarters() (1-4)moment().quarter(Number) or .quarters(Number) (1-4)
Yearmoment().year() or .years()moment().year(Number) or .years(Number)
Week Yearmoment().weekYear() (Locale aware)moment().weekYear(Number)
ISO Week Yearmoment().isoWeekYear()moment().isoWeekYear(Number)
Weeks in Yearmoment().weeksInYear() (Locale aware)N/A
ISO Weeks in Yearmoment().isoWeeksInYear()N/A

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 hour
const 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')); // Unchanged
console.log('Safely Modified:', safeModified.format('YYYY-MM-DD HH:mm:ss'));
// Using generic set
const 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'));

Moment.js can easily find the earliest or latest moment from a list:

  • moment.max(Moment[, Moment...]) or moment.max(Moment[]): Returns the latest Moment object from the provided arguments or array.
  • moment.min(Moment[, Moment...]) or moment.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-15
console.log('Earliest:', earliestDate.format('YYYY-MM-DD')); // Output: Earliest: 2023-10-01

Getters 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/