UNPKG

@intility/bifrost-react

Version:

React library for Intility's design system, Bifrost.

37 lines (33 loc) 1.41 kB
/** * Calculate milliseconds until the next unit boundary for relative time updates * @param date The target date * @returns milliseconds until next update should occur */ export default function getNextUpdateDelay(date) { const now = new Date(); const diffMs = now.getTime() - date.getTime(); const absDiffMs = Math.abs(diffMs); const isFuture = diffMs < 0; const SECOND_MS = 1000; const MINUTE_MS = 60 * SECOND_MS; const HOUR_MS = 60 * MINUTE_MS; const DAY_MS = 24 * HOUR_MS; // If it's been 2+ days, update at the next day boundary if (absDiffMs >= 2 * DAY_MS) { const msIntoCurrentDay = absDiffMs % DAY_MS; return isFuture ? msIntoCurrentDay || DAY_MS : DAY_MS - msIntoCurrentDay; } // If it's been 2+ hours, update at the next hour boundary if (absDiffMs >= 2 * HOUR_MS) { const msIntoCurrentHour = absDiffMs % HOUR_MS; return isFuture ? msIntoCurrentHour || HOUR_MS : HOUR_MS - msIntoCurrentHour; } // If it's been 2+ minutes, update at the next minute boundary if (absDiffMs >= 2 * MINUTE_MS) { const msIntoCurrentMinute = absDiffMs % MINUTE_MS; return isFuture ? msIntoCurrentMinute || MINUTE_MS : MINUTE_MS - msIntoCurrentMinute; } // If it's been seconds, update at the next second boundary const msIntoCurrentSecond = absDiffMs % SECOND_MS; return isFuture ? msIntoCurrentSecond || SECOND_MS : SECOND_MS - msIntoCurrentSecond; }