All files / libs/ext/dates/src/lib timestamps.ts

100% Statements 31/31
100% Branches 7/7
100% Functions 2/2
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 321x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x  
import { isValid } from 'date-fns';
 
import { assert } from '@amalia/ext/typescript';
 
export type UnixTimestampInSeconds = number;
 
/**
 * Get the Unix timestamp (in seconds) of the given date.
 * - Decimal values are rounded.
 * - Number inputs are treated as Unix timestamps.
 */
export const toTimestamp = <TDate extends Date>(v: TDate | UnixTimestampInSeconds): UnixTimestampInSeconds => {
  const timestamp = typeof v === 'number' ? v : Math.floor(new Date(v).getTime() / 1000);
 
  assert(timestamp && Number.isFinite(timestamp), `Invalid date ${v}`);
 
  return timestamp;
};
 
/**
 * Create a `Date` from a Unix timestamp (in seconds).
 * - Date inputs are cloned.
 * - Number inputs are treated as Unix timestamp (in seconds).
 */
export const toDate = (v: Date | UnixTimestampInSeconds | string): Date => {
  const date = new Date(typeof v === 'number' ? v * 1000 : v);
 
  assert(isValid(date), `Invalid timestamp ${v}`);
 
  return date;
};