📜  startOfDay 和 endOfDay (1)

📅  最后修改于: 2023-12-03 14:47:42.527000             🧑  作者: Mango

startOfDay and endOfDay in Moment.js

In Moment.js, startOfDay() and endOfDay() are two commonly used methods to manipulate dates.

startOfDay()

The startOfDay() method returns a new date object that represents the start of the day for the given date object. The start of the day is considered to be midnight (00:00:00).

Syntax:

moment().startOfDay();

Example:

const today = moment(); // current date and time
const startOfDay = today.startOfDay(); // start of today

console.log(startOfDay.toString()); // Sat Sep 04 2021 00:00:00 GMT+0530 (India Standard Time)
endOfDay()

The endOfDay() method is used to get a new date object that represents the end of the day for the given date object. The end of the day is considered to be just before midnight (23:59:59).

Syntax:

moment().endOfDay();

Example:

const today = moment(); // current date and time
const endOfDay = today.endOfDay(); // end of today

console.log(endOfDay.toString()); // Sat Sep 04 2021 23:59:59 GMT+0530 (India Standard Time)
Usage

startOfDay() and endOfDay() can be used together to get all the dates within a day range.

Example:

const startDate = moment().startOfDay();
const endDate = moment().endOfDay();

for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'minutes')) {
    console.log(m.toString()); // output all the dates and times within today's range at 1 minute interval 
}

This will output all the dates within today's range at a 1-minute interval.

Conclusion

In conclusion, startOfDay() and endOfDay() are useful methods in Moment.js to manipulate dates and get the start and end of the day for any given date. They can be used together to get all the dates within a day range, making them useful in various applications.