Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(datetime): format() options #4285

Merged
merged 6 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
);
}

/** The options used for formatting date in {@linkcode format}. */
iuioiua marked this conversation as resolved.
Show resolved Hide resolved
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 },
),
);
},
});
Loading