diff --git a/src/functions/dates.spec.ts b/src/functions/dates.spec.ts new file mode 100644 index 0000000..eeab7c5 --- /dev/null +++ b/src/functions/dates.spec.ts @@ -0,0 +1,11 @@ +import {lastModifiedHeaderDate} from '../index' + +describe('Dates', () => { + it('should generate a last modified date', () => { + const timeString = "Wed Apr 6 2022 09:38:39 GMT+0100 (British Summer Time)" + + const lastModified = lastModifiedHeaderDate(timeString) + + expect(lastModified).toBe('Wed, 06 Apr 2022 08:38:39 GMT') + }) +}) \ No newline at end of file diff --git a/src/functions/dates.ts b/src/functions/dates.ts new file mode 100644 index 0000000..350c065 --- /dev/null +++ b/src/functions/dates.ts @@ -0,0 +1,46 @@ +const dateOrStringFunction = (fn: (date: Date) => ReturnType) => { + return (date: Date | String) => { + if (typeof date === 'string') { + date = new Date(date) + } + + return fn(date as Date) + } +} + +/** + * Takes a date (or string) and returns it formatted as a last modified header date. + * + * @param date A `Date` or date string to be converted. + * @returns The given date in the required format for `Last-Modified` headers. + */ +export const lastModifiedHeaderDate = dateOrStringFunction(date => { + date = new Date(date.toLocaleString('en-US', {timeZone: 'GMT'})) + + const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] + const months = [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec' + ] + + return `${days[date.getDay()]}, ${date + .getDate() + .toString() + .padStart(2, '0')} ${months[date.getMonth()]} ${date.getFullYear()} ${date + .getHours() + .toString() + .padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date + .getSeconds() + .toString() + .padStart(2, '0')} GMT` +}) diff --git a/src/index.ts b/src/index.ts index f500c38..33be85e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ export { numberToVh, numberToVw } from './functions/css' +export {lastModifiedHeaderDate} from './functions/dates' export {deepIncludesArray} from './functions/deep-includes' export {defaults} from './functions/defaults' export {diffArray} from './functions/diff-array'