Manipulate Date And Time
Modern Date/Time: Manipulating with Moment.js
Section titled “Modern Date/Time: Manipulating with Moment.js”Moment.js provides intuitive methods for modifying date and time values, such as adding or subtracting time units, or moving to the start or end of a specific time period.
Crucial Reminder: Mutability! Most manipulation methods in Moment.js mutate the original Moment object. If you need to preserve the original date, always clone() the moment before manipulating it. Failure to do so is a common source of bugs.
// Example of mutationconst originalMoment = moment('2023-10-26');const addedMoment = originalMoment.add(1, 'day');
console.log(originalMoment.format('YYYY-MM-DD')); // Output: 2023-10-27 (MUTATED!)console.log(addedMoment.format('YYYY-MM-DD')); // Output: 2023-10-27
// Correct way using clone()const safeOriginal = moment('2023-10-26');const safeAdded = safeOriginal.clone().add(1, 'day');
console.log(safeOriginal.format('YYYY-MM-DD')); // Output: 2023-10-26 (Preserved)console.log(safeAdded.format('YYYY-MM-DD')); // Output: 2023-10-27Common Manipulation Methods
Section titled “Common Manipulation Methods”Here are the key methods for date/time manipulation:
| Method | Description & Syntax |
|---|---|
| Add | Adds a specified amount of time.moment().add(Number, String) (e.g., add(7, 'days'))moment().add(Duration) (e.g., add(moment.duration(2, 'hours')))moment().add(Object) (e.g., add({ days: 7, hours: 2 })) |
| Subtract | Subtracts a specified amount of time.moment().subtract(Number, String) (e.g., subtract(3, 'months'))moment().subtract(Duration)moment().subtract(Object) (e.g., subtract({ weeks: 1, minutes: 30 })) |
| Start of Time | Sets the moment to the beginning of a specified unit of time.moment().startOf(String) (e.g., startOf('day'), startOf('month'), startOf('year'), startOf('hour'))moment('2023-10-26T15:30:45').startOf('day'); // Becomes 2023-10-26T00:00:00moment('2023-10-26T15:30:45').startOf('month'); // Becomes 2023-10-01T00:00:00 |
| End of Time | Sets the moment to the end of a specified unit of time.moment().endOf(String) (e.g., endOf('day'), endOf('month'), endOf('week'))moment('2023-10-26T15:30:45').endOf('day'); // Becomes 2023-10-26T23:59:59.999moment('2023-10-26T15:30:45').endOf('month'); // Becomes 2023-10-31T23:59:59.999 |
| Local Mode | Sets the moment to use local time mode (this is usually the default).moment().local();Useful for converting a UTC moment back to local time. |
| UTC Mode | Sets the moment to use UTC mode.moment().utc();Operations after this will interpret the date/time as UTC. |
| UTC Offset | Sets or gets the UTC offset in minutes.moment().utcOffset(); // Get current offsetmoment().utcOffset(Number|String); // Set offset (e.g., utcOffset(120) or utcOffset('+02:00'))moment().utcOffset(Number, keepLocalTime); // boolean: if true, keeps local time and changes offset |
Supported Units for Manipulation
Section titled “Supported Units for Manipulation”The string units accepted by add, subtract, startOf, endOf include (case-insensitive, singular or plural):
'year','y''quarter','Q''month','M''week','w''isoWeek''day','d''date'(alias for ‘day’)'hour','h''minute','m''second','s''millisecond','ms'
Example: Calculating a Due Date
Section titled “Example: Calculating a Due Date”const orderDate = moment('2023-10-26T11:00:00');const processingTime = { days: 2 }; // 2 business days (simplified)const shippingTime = moment.duration(3, 'days'); // 3 calendar days
// Clone before manipulatinglet estimatedShipDate = orderDate.clone().add(processingTime);
// Example: Skip weekends (simple implementation)while (estimatedShipDate.day() === 0 || estimatedShipDate.day() === 6) { // Sunday=0, Saturday=6 estimatedShipDate.add(1, 'day');}
const estimatedDeliveryDate = estimatedShipDate.clone().add(shippingTime);
console.log('Order Date:', orderDate.format('LLLL'));console.log('Estimated Ship Date:', estimatedShipDate.format('LLLL'));console.log('Estimated Delivery Date:', estimatedDeliveryDate.format('LLLL'));
// Get start of the delivery weekconst deliveryWeekStart = estimatedDeliveryDate.clone().startOf('week');console.log('Delivery Week Starts On:', deliveryWeekStart.format('LL'));
/* Example Output (assuming Oct 26 2023 was a Thursday):Order Date: Thursday, October 26, 2023 11:00 AMEstimated Ship Date: Monday, October 30, 2023 11:00 AMEstimated Delivery Date: Thursday, November 2, 2023 11:00 AMDelivery Week Starts On: 10/29/2023*/This example demonstrates combining add with different inputs (object, duration) and startOf, always using clone to ensure non-destructive operations.
Mastering manipulation requires understanding mutability. Check the docs: https://momentjs.com/docs/#/manipulating/