Answers for "js get quater hours in time range"

0

js get quater hours in time range

// Start and End is the UTC-Timestamp
function getQuaterHours(start: number, end: number): Date[] {
    const difference = end - start;

  // Return if Difference between start and end is 0
    if (difference <= 0) {
      // You can return a default range if difference is 0
        return [];
    }

  // Maybe you have to play a bit between .getUTCHours and .getHours- Method
    const hours = new Date(difference).getUTCHours();

    const startMinutes = new Date(start).getMinutes();
    const endMinutes = new Date(end).getMinutes();

  // Describes 4 Quaters / Hour * Hours in Difference
  // between start and end
    const factor = hours * 4 + Math.round(startMinutes / 15) + Math.round(endMinutes / 15)

    const results: Date[] = [];

  // For each element, round to next Higher quater
    for (let index = 0; index <= factor; index++) {
        const time = new Date(start + (index * difference / factor));
        time.setMinutes(roundToNextQuater(time.getMinutes()));
        results.push(new Date(time));
    }

    return results;
}

// Function to round to next quater
// If you want to round to next lower quater, use .floor()
// instead of .ceil()
function roundToNextQuater(minutes: number): number {
    return (Math.ceil(minutes / 15) * 15) % 60;
}
Posted by: Guest on July-27-2021

Code answers related to "TypeScript"

Browse Popular Code Answers by Language