summaryrefslogtreecommitdiff
path: root/datetime
diff options
context:
space:
mode:
authorVincent LE GOFF <g_n_s@hotmail.fr>2019-04-28 01:07:11 +0200
committerRyan Dahl <ry@tinyclouds.org>2019-04-27 16:07:11 -0700
commitce101a0f8632f6b5390af247f3df2002e86becdf (patch)
tree5232eb3cbd21c8773881327f98162f0567dfe543 /datetime
parent8d49022ef67b590d8ee7b3ff984307b6c0a69d4f (diff)
http: Cookie improvements (denoland/deno_std#359)
Original: https://github.com/denoland/deno_std/commit/f1114691038888fc3d8995b64a8028f072569672
Diffstat (limited to 'datetime')
-rw-r--r--datetime/mod.ts39
-rw-r--r--datetime/test.ts9
2 files changed, 48 insertions, 0 deletions
diff --git a/datetime/mod.ts b/datetime/mod.ts
index a5c2648b0..4d627fcbe 100644
--- a/datetime/mod.ts
+++ b/datetime/mod.ts
@@ -1,4 +1,6 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
+import { pad } from "../strings/pad.ts";
+
export type DateFormat = "mm-dd-yyyy" | "dd-mm-yyyy" | "yyyy-mm-dd";
/**
@@ -105,3 +107,40 @@ export function dayOfYear(date: Date): number {
export function currentDayOfYear(): number {
return dayOfYear(new Date());
}
+
+/**
+ * Parse a date to return a IMF formated string date
+ * RFC: https://tools.ietf.org/html/rfc7231#section-7.1.1.1
+ * IMF is the time format to use when generating times in HTTP
+ * headers. The time being formatted must be in UTC for Format to
+ * generate the correct format.
+ * @param date Date to parse
+ * @return IMF date formated string
+ */
+export function toIMF(date: Date): string {
+ function dtPad(v: string, lPad: number = 2): string {
+ return pad(v, lPad, { char: "0" });
+ }
+ const d = dtPad(date.getUTCDate().toString());
+ const h = dtPad(date.getUTCHours().toString());
+ const min = dtPad(date.getUTCMinutes().toString());
+ const s = dtPad(date.getUTCSeconds().toString());
+ const y = date.getUTCFullYear();
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thus", "Fri", "Sat"];
+ const months = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec"
+ ];
+ return `${days[date.getDay()]}, ${d} ${
+ months[date.getUTCMonth()]
+ } ${y} ${h}:${min}:${s} GMT`;
+}
diff --git a/datetime/test.ts b/datetime/test.ts
index 95bcd3653..f47914728 100644
--- a/datetime/test.ts
+++ b/datetime/test.ts
@@ -74,3 +74,12 @@ test(function DayOfYear(): void {
test(function currentDayOfYear(): void {
assertEquals(datetime.currentDayOfYear(), datetime.dayOfYear(new Date()));
});
+
+test({
+ name: "[DateTime] to IMF",
+ fn(): void {
+ const actual = datetime.toIMF(new Date(Date.UTC(1994, 3, 5, 15, 32)));
+ const expected = "Tue, 05 May 1994 15:32:00 GMT";
+ assertEquals(actual, expected);
+ }
+});