John
John

Reputation: 4991

Time round up quarter without condition

I need to round up quarter my time even if I'm on the current quarter. Here is my code :

const currentDate = new Date(2020, 1, 8, 9, 42, 0, 0);
let roundedUpQuarter = Math.ceil(currentDate.getMinutes() / 15) * 15 % 60;

So in my exemple the current time is 09:42 so in my roundedUpQuarter variable I'll get the good result 09:45 But I have a problem when I send 0, 15, 30 or 45 minutes on my current time because I need to round up too.

For an example if my current time is 09:30 I need to get 09:45

I don't want to use if condition to do that. It's possible to do this only with a formula ?

Upvotes: 0

Views: 39

Answers (2)

Matt Miguel
Matt Miguel

Reputation: 1375

const currentDate = new Date(2020, 1, 8, 9, 42, 0, 0);
let roundedUpQuarter = Math.ceil((currentDate.getMinutes()+0.1) / 15) * 15 % 60;

Upvotes: 3

pavel
pavel

Reputation: 27092

Check % 15 === 0 and add 1 minute to real minutes. Than continue with your equation.

const currentDate = new Date(2020, 1, 8, 9, 45, 0, 0);
var minutes = currentDate.getMinutes() % 15 === 0 ? (currentDate.getMinutes() + 1) : currentDate.getMinutes();
let roundedUpQuarter = Math.ceil(minutes / 15) * 15 % 60;

console.log(roundedUpQuarter); // for 45 return 0

Upvotes: 0

Related Questions