'How to set start day time to particular time in momentjs
I'm trying to set the start time of the day to a particular time. currently, in momentjs, I can get startOf day like this
let now = moment()
console.log('now', now.toString())
console.log('start Day', now.startOf('day').toString()) // Thu Oct 07 2021 00:00:00 GMT+0530
console.log('end day', now.endOf('day').toString()) //Thu Oct 07 2021 23:59:59 GMT+0530
is there any way so I can set my day start from particular time like I want to start my day from
Thu Oct 07 2021 08:00:00 GMT+0530
and end on
Thu Oct 07 2021 07:59:59 GMT+0530
Solution 1:[1]
You should probably write your own function in order to achieve this.
function customStartOf(momentObj) {
return momentObj.clone().startOf('day').hours(8);
}
function customEndOf(momentObj) {
// I assume that end of the day is bigger than start of the day
return momentObj.clone().endOf('day').add(1, 'days').hours(7);
}
let now = moment();
console.log('now', now.toString()) ;
console.log('start Day', now.startOf('day').toString());
console.log('end day', now.endOf('day').toString());
console.log('custom start Day', customStartOf(now).toString());
console.log('custom end day', customEndOf(now).toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Solution 2:[2]
You have to take into account the timezone.
let myDate = new Date();
const timezoneOffset = moment(myDate).utcOffset();
moment(myDate).utc().add(timezoneOffset, 'minutes').startOf('day').format();
moment(myDate).utc().add(timezoneOffset, 'minutes').endOf('day').format();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Bank5z0rSqt |