0

I need to convert the decimal hours minutes value(ex: 2.36 - hours.minutes) to the nearest quarter hours (2.25). Is there any way to do it in Angular using typescript. the input will be 2.36 and I need to convert it into 2.25(where .25 is quarter-hour for 36 mins). I did it in C# using Timespan like below-

var time = TimeSpan.FromHours(2.36) // time: {02:21:36}
decimal round = (decimal)time.Minutes / 15;  // round : 1.4M
round = Decimal.Round(round, MidpointRounding.AwayFromZero)*15;//round :15
var roundedTime = (float)(new TimeSpan(time.Hours, (int)round, 0).TotalHours); // o/p roundedTime: 2.25

Is there any TimeSpan equivalent in typescript or conversion for above c# to typescript? Thanks in advance!

Mahendra
  • 1
  • 1

3 Answers3

0

There is no Angular/Typescript specific way to achieve this, but you can rewrite some of the functions from THIS question that seems to fit your problem well. I mostly refer to this question, because it's not entirely clear how your value arrives. Is it a Date Object, or do you get a String?

abim
  • 33
  • 6
  • I tired https://stackoverflow.com/questions/4968250/how-to-round-time-to-the-nearest-quarter-hour-in-javascript but not working for me I am getting value 30 but expected is 25 let hours = 2; let minutes = 36; m = (Math.round(minutes / 15) * 15) % 60; // m=30 h = minutes > 52 ? (+hours === 23 ? 0 : ++hours) : hours; const roundedTime = Number(h + '.' + m * 100); – Mahendra Mar 17 '20 at 00:35
0

I would recommend Moment.js if you're doing anything even slightly complicated with dates or times in Javascript or Typescript. Here are the typescript installation instructions: https://momentjs.com/docs/#/use-it/typescript/

And there is a plugin called moment-round which will do exactly what you are suggesting: https://momentjs.com/docs/#/plugins/round/

andyvanee
  • 958
  • 9
  • 21
0

I found the below solution to fulfill my requirement. Its working for me as expected. But make sure you are covered edge case scenarios. enjoy!!!!

const roundedTime = (Math.round(input * 4) / 4 ).toFixed(2);
Mahendra
  • 1
  • 1