Skip to content

Commit

Permalink
feat: add a date formatting function for Last-Modified headers
Browse files Browse the repository at this point in the history
  • Loading branch information
Arcath committed Apr 13, 2022
1 parent b298f00 commit 309fa97
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/functions/dates.spec.ts
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')
})
})
46 changes: 46 additions & 0 deletions src/functions/dates.ts
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`
})
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down

0 comments on commit 309fa97

Please sign in to comment.