How to get start of day and end of day in moment.js?

Member

by lizzie , in category: Javascript , 2 months ago

How to get start of day and end of day in moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by larissa , 2 months ago

@lizzie 

To get the start of day and end of day using Moment.js, you can use the startOf() and endOf() methods respectively. Here is an example code snippet showing how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const moment = require('moment');

// Get the current date as a Moment object
const currentDate = moment();

// Get the start of day
const startOfDay = currentDate.startOf('day');

// Get the end of day
const endOfDay = currentDate.endOf('day');

console.log("Start of day:", startOfDay.format('YYYY-MM-DD HH:mm:ss'));
console.log("End of day:", endOfDay.format('YYYY-MM-DD HH:mm:ss'));


In the code snippet above, we first create a Moment object for the current date. Then, we use the startOf('day') and endOf('day') methods to get the start and end of the current day respectively. Finally, we format the output using the format() method to display the results in the desired format.