From ce101a0f8632f6b5390af247f3df2002e86becdf Mon Sep 17 00:00:00 2001 From: Vincent LE GOFF Date: Sun, 28 Apr 2019 01:07:11 +0200 Subject: http: Cookie improvements (denoland/deno_std#359) Original: https://github.com/denoland/deno_std/commit/f1114691038888fc3d8995b64a8028f072569672 --- datetime/mod.ts | 39 +++++++++++++++++++++++++++++++++++++++ datetime/test.ts | 9 +++++++++ 2 files changed, 48 insertions(+) (limited to 'datetime') 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); + } +}); -- cgit v1.2.3