Skip to content

Commit

Permalink
feat(datetime): format() options (#4285)
Browse files Browse the repository at this point in the history
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
  • Loading branch information
babiabeo and iuioiua authored Feb 9, 2024
1 parent 57fc775 commit 2b5149e
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
26 changes: 21 additions & 5 deletions datetime/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
18 changes: 18 additions & 0 deletions datetime/format_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
),
);
},
});

0 comments on commit 2b5149e

Please sign in to comment.