Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2b5149e

Browse files
babiabeoiuioiua
andauthoredFeb 9, 2024
feat(datetime): format() options (denoland#4285)
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
1 parent 57fc775 commit 2b5149e

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed
 

‎datetime/format.ts

+21-5
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,29 @@ import { DateTimeFormatter } from "./_common.ts";
1818
* format(new Date(2019, 0, 20, 16, 34), "HH:mm MM-dd-yyyy"); // output : "16:34 01-20-2019"
1919
* format(new Date(2019, 0, 20, 16, 34, 23, 123), "MM-dd-yyyy HH:mm:ss.SSS"); // output : "01-20-2019 16:34:23.123"
2020
* format(new Date(2019, 0, 20), "'today:' yyyy-MM-dd"); // output : "today: 2019-01-20"
21+
* format(new Date("2019-01-20T16:34:23:123-05:00"), "yyyy-MM-dd HH:mm:ss", { utc: true });
22+
* // output : "2019-01-20 21:34:23"
2123
* ```
2224
*
23-
* @param date Date
24-
* @param formatString Format string
25-
* @return formatted date string
25+
* @param date The date to be formatted.
26+
* @param formatString The date time string format.
27+
* @param options The options to customize the formatting of the date.
28+
* @return The formatted date string.
2629
*/
27-
export function format(date: Date, formatString: string): string {
30+
export function format(
31+
date: Date,
32+
formatString: string,
33+
options: FormatOptions = {},
34+
): string {
2835
const formatter = new DateTimeFormatter(formatString);
29-
return formatter.format(date);
36+
return formatter.format(
37+
date,
38+
options.utc ? { timeZone: "UTC" } : undefined,
39+
);
40+
}
41+
42+
/** Options for {@linkcode format}. */
43+
export interface FormatOptions {
44+
/** Whether returns the formatted date in UTC instead of local time. */
45+
utc?: boolean;
3046
}

‎datetime/format_test.ts

+18
Original file line numberDiff line numberDiff line change
@@ -102,5 +102,23 @@ Deno.test({
102102
"1",
103103
format(new Date("2019-01-01T13:00:00.000"), "h"),
104104
);
105+
106+
assertEquals(
107+
"2019-01-01 04:00:00.000",
108+
format(
109+
new Date("2019-01-01T13:00:00.000+09:00"),
110+
"yyyy-MM-dd HH:mm:ss.SSS",
111+
{ utc: true },
112+
),
113+
);
114+
115+
assertEquals(
116+
"2019-01-01 18:00:00.000",
117+
format(
118+
new Date("2019-01-01T13:00:00.000-05:00"),
119+
"yyyy-MM-dd HH:mm:ss.SSS",
120+
{ utc: true },
121+
),
122+
);
105123
},
106124
});

0 commit comments

Comments
 (0)
Please sign in to comment.