All files / app/utils date.ts

69.56% Statements 16/23
100% Branches 5/5
71.42% Functions 5/7
69.56% Lines 16/23

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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59  24x       24x   24x 76x         24x 33x           24x             1381x                     35x                 35x       24x 24x 24x 24x 24x 24x    
// format a date
import { Duration as DurationPb } from "google-protobuf/google/protobuf/duration_pb";
import { Timestamp } from "google-protobuf/google/protobuf/timestamp_pb";
 
import { Dayjs, Duration } from "./dayjs";
import { dayMillis } from "./timeAgo";
 
const dateTimeFormatter = (locale: string) =>
  new Intl.DateTimeFormat(locale, {
    month: "short",
    year: "numeric",
  });
 
const dateFormatter = (locale: string) =>
  new Intl.DateTimeFormat(locale, {
    year: "numeric",
    month: "short",
    day: "2-digit",
  });
 
const numNights = (date1: string, date2: string) => {
  const diffTime = Date.parse(date1) - Date.parse(date2);
  const diffDays = Math.ceil(diffTime / dayMillis);
  return diffDays;
};
 
function timestamp2Date(timestamp: Timestamp.AsObject): Date {
  return new Date(Math.floor(timestamp.seconds * 1e3 + timestamp.nanos / 1e6));
}
 
function duration2pb(duration: Duration) {
  const d = new DurationPb();
  d.setSeconds(duration.asSeconds());
  d.setNanos(duration.milliseconds() * 1000);
  return d;
}
 
function isSameDate(date1: Dayjs, date2: Dayjs): boolean {
  return (
    date1.month() === date2.month() &&
    date1.year() === date2.year() &&
    date1.date() === date2.date()
  );
}
 
/** Compares whether date1 is equal to or in the future of date2 */
function isSameOrFutureDate(date1: Dayjs, date2: Dayjs): boolean {
  return isSameDate(date1, date2) || date1.isAfter(date2);
}
 
export {
  dateFormatter,
  dateTimeFormatter,
  duration2pb,
  isSameOrFutureDate,
  numNights,
  timestamp2Date,
};