From 2b5149ebdaec74f76d4d69639f76599129391ac6 Mon Sep 17 00:00:00 2001 From: David Luis <95457148+babiabeo@users.noreply.github.com> Date: Fri, 9 Feb 2024 17:35:14 +0700 Subject: [PATCH] feat(datetime): `format()` options (#4285) Co-authored-by: Asher Gomez --- datetime/format.ts | 26 +++++++++++++++++++++----- datetime/format_test.ts | 18 ++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/datetime/format.ts b/datetime/format.ts index 09cc68d4c15b..f4e8b40d30e4 100644 --- a/datetime/format.ts +++ b/datetime/format.ts @@ -18,13 +18,29 @@ import { DateTimeFormatter } from "./_common.ts"; * format(new Date(2019, 0, 20, 16, 34), "HH:mm MM-dd-yyyy"); // output : "16:34 01-20-2019" * 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" * format(new Date(2019, 0, 20), "'today:' yyyy-MM-dd"); // output : "today: 2019-01-20" + * format(new Date("2019-01-20T16:34:23:123-05:00"), "yyyy-MM-dd HH:mm:ss", { utc: true }); + * // output : "2019-01-20 21:34:23" * ``` * - * @param date Date - * @param formatString Format string - * @return formatted date string + * @param date The date to be formatted. + * @param formatString The date time string format. + * @param options The options to customize the formatting of the date. + * @return The formatted date string. */ -export function format(date: Date, formatString: string): string { +export function format( + date: Date, + formatString: string, + options: FormatOptions = {}, +): string { const formatter = new DateTimeFormatter(formatString); - return formatter.format(date); + return formatter.format( + date, + options.utc ? { timeZone: "UTC" } : undefined, + ); +} + +/** Options for {@linkcode format}. */ +export interface FormatOptions { + /** Whether returns the formatted date in UTC instead of local time. */ + utc?: boolean; } diff --git a/datetime/format_test.ts b/datetime/format_test.ts index 0023ca89e1f1..b4acdb3a55d9 100644 --- a/datetime/format_test.ts +++ b/datetime/format_test.ts @@ -102,5 +102,23 @@ Deno.test({ "1", format(new Date("2019-01-01T13:00:00.000"), "h"), ); + + assertEquals( + "2019-01-01 04:00:00.000", + format( + new Date("2019-01-01T13:00:00.000+09:00"), + "yyyy-MM-dd HH:mm:ss.SSS", + { utc: true }, + ), + ); + + assertEquals( + "2019-01-01 18:00:00.000", + format( + new Date("2019-01-01T13:00:00.000-05:00"), + "yyyy-MM-dd HH:mm:ss.SSS", + { utc: true }, + ), + ); }, });