datetime.ts 2.01 KB
Newer Older
1
import { DateTimeFormatOptions } from "vue-i18n";
2
import { i18n } from "../utils/i18n";
3

4
5
6
7
8
function parseDateTime(value: string): Date {
  return new Date(value);
}

function formatDateString(value: string): string {
9
  return parseDateTime(value).toLocaleString(locale(), {
10
11
12
13
14
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
15
16
}

Thomas Citharel's avatar
Thomas Citharel committed
17
function formatTimeString(value: string, timeZone: string): string {
18
  return parseDateTime(value).toLocaleTimeString(locale(), {
Thomas Citharel's avatar
Thomas Citharel committed
19
20
    hour: "numeric",
    minute: "numeric",
Thomas Citharel's avatar
Thomas Citharel committed
21
    timeZone,
Thomas Citharel's avatar
Thomas Citharel committed
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
// TODO: These can be removed in favor of dateStyle/timeStyle when those two have sufficient support
// https://caniuse.com/mdn-javascript_builtins_intl_datetimeformat_datetimeformat_datestyle
const LONG_DATE_FORMAT_OPTIONS: DateTimeFormatOptions = {
  weekday: undefined,
  year: "numeric",
  month: "long",
  day: "numeric",
  hour: undefined,
  minute: undefined,
};

const LONG_TIME_FORMAT_OPTIONS: DateTimeFormatOptions = {
  weekday: "long",
  hour: "numeric",
  minute: "numeric",
};

const SHORT_DATE_FORMAT_OPTIONS: DateTimeFormatOptions = {
  weekday: undefined,
  year: "numeric",
  month: "short",
  day: "numeric",
  hour: undefined,
  minute: undefined,
};

const SHORT_TIME_FORMAT_OPTIONS: DateTimeFormatOptions = {
  weekday: "short",
  hour: "numeric",
  minute: "numeric",
};

function formatDateTimeString(
  value: string,
59
  timeZone: string | null | undefined = undefined,
60
61
62
63
64
65
66
  showTime = true,
  dateFormat = "long"
): string {
  const isLongFormat = dateFormat === "long";
  let options = isLongFormat
    ? LONG_DATE_FORMAT_OPTIONS
    : SHORT_DATE_FORMAT_OPTIONS;
Thomas Citharel's avatar
Thomas Citharel committed
67
  if (showTime) {
68
69
70
    options = {
      ...options,
      ...(isLongFormat ? LONG_TIME_FORMAT_OPTIONS : SHORT_TIME_FORMAT_OPTIONS),
71
      timeZone: timeZone || undefined,
72
    };
Thomas Citharel's avatar
Thomas Citharel committed
73
  }
74
  const format = new Intl.DateTimeFormat(locale(), options);
75
  return format.format(parseDateTime(value));
76
77
}

78
79
const locale = () => i18n.locale.replace("_", "-");

80
export { formatDateString, formatTimeString, formatDateTimeString };