UNPKG

2.84 kBJavaScriptView Raw
1import { addLeadingZeros } from "./_lib/addLeadingZeros.js";
2import { isValid } from "./isValid.js";
3import { toDate } from "./toDate.js";
4
5/**
6 * The {@link formatISO9075} function options.
7 */
8
9/**
10 * @name formatISO9075
11 * @category Common Helpers
12 * @summary Format the date according to the ISO 9075 standard (https://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_get-format).
13 *
14 * @description
15 * Return the formatted date string in ISO 9075 format. Options may be passed to control the parts and notations of the date.
16 *
17 * @param date - The original date
18 * @param options - An object with options.
19 *
20 * @returns The formatted date string
21 *
22 * @throws `date` must not be Invalid Date
23 *
24 * @example
25 * // Represent 18 September 2019 in ISO 9075 format:
26 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52))
27 * //=> '2019-09-18 19:00:52'
28 *
29 * @example
30 * // Represent 18 September 2019 in ISO 9075, short format:
31 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { format: 'basic' })
32 * //=> '20190918 190052'
33 *
34 * @example
35 * // Represent 18 September 2019 in ISO 9075 format, date only:
36 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'date' })
37 * //=> '2019-09-18'
38 *
39 * @example
40 * // Represent 18 September 2019 in ISO 9075 format, time only:
41 * const result = formatISO9075(new Date(2019, 8, 18, 19, 0, 52), { representation: 'time' })
42 * //=> '19:00:52'
43 */
44export function formatISO9075(date, options) {
45 const date_ = toDate(date, options?.in);
46
47 if (!isValid(date_)) {
48 throw new RangeError("Invalid time value");
49 }
50
51 const format = options?.format ?? "extended";
52 const representation = options?.representation ?? "complete";
53
54 let result = "";
55
56 const dateDelimiter = format === "extended" ? "-" : "";
57 const timeDelimiter = format === "extended" ? ":" : "";
58
59 // Representation is either 'date' or 'complete'
60 if (representation !== "time") {
61 const day = addLeadingZeros(date_.getDate(), 2);
62 const month = addLeadingZeros(date_.getMonth() + 1, 2);
63 const year = addLeadingZeros(date_.getFullYear(), 4);
64
65 // yyyyMMdd or yyyy-MM-dd.
66 result = `${year}${dateDelimiter}${month}${dateDelimiter}${day}`;
67 }
68
69 // Representation is either 'time' or 'complete'
70 if (representation !== "date") {
71 const hour = addLeadingZeros(date_.getHours(), 2);
72 const minute = addLeadingZeros(date_.getMinutes(), 2);
73 const second = addLeadingZeros(date_.getSeconds(), 2);
74
75 // If there's also date, separate it with time with a space
76 const separator = result === "" ? "" : " ";
77
78 // HHmmss or HH:mm:ss.
79 result = `${result}${separator}${hour}${timeDelimiter}${minute}${timeDelimiter}${second}`;
80 }
81
82 return result;
83}
84
85// Fallback for modularized imports:
86export default formatISO9075;