-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add a date formatting function for Last-Modified headers
- Loading branch information
Showing
3 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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') | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
const dateOrStringFunction = <ReturnType>(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` | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters