gurbajani
gurbajani

Reputation: 121

MomentJS add hours up to 24

I have to solve this problem : in code I might have moment times that look like this

{ start: '2020-08-03T00:00:00Z', end: '2020-08-03T23:59:59Z' }

or

{ start: '2020-08-03T15:11:51Z', end: '2020-08-04T15:11:50Z' }

If there is start time that is 00:00 I want to add 24 hours so that between start and end I get the whole day (meaning this objects represents one day)

But if start has any time more that 00:00, let's say 2020-08-03T15:11:51Z then I want to add precisely the amount of time which will result for end to be 2020-08-03T23:59:59Z

Right now in my case it adds 24 hours and it goes beyond 08-03 and results in 08-04 logically

I add time in moment like this:

.add(23, 'hours').add(59.999999, 'minutes').format()

Is there a simple way in moment to indicate this information like "if" and add necessary time up to 24 to fill the day ? Thanks

Upvotes: 0

Views: 37

Answers (1)

AlTheLazyMonkey
AlTheLazyMonkey

Reputation: 1242

If you want get everytime the end of day you can use .endOf('day') if you want get the end of the day

const obj1 = { start: '2020-08-03T00:00:00Z', end: '2020-08-03T23:59:59Z' }

console.log(moment(obj1.start).endOf('day'));

const obj2 = { start: '2020-08-03T15:11:51Z', end: '2020-08-04T15:11:50Z' }

console.log(moment(obj2.start).endOf('day'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Upvotes: 1

Related Questions