This repository has been archived by the owner on Mar 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
64 lines (57 loc) · 1.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import toDate from '../toDate/index.ts'
import isValid from '../isValid/index.js'
import addLeadingZeros from '../_lib/addLeadingZeros/index.js'
const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
const months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
]
/**
* @name formatRFC7231
* @category Common Helpers
* @summary Format the date according to the RFC 7231 standard (https://tools.ietf.org/html/rfc7231#section-7.1.1.1).
*
* @description
* Return the formatted date string in RFC 7231 format.
* The result will always be in UTC timezone.
*
* @param {Date|Number} date - the original date
* @returns {String} the formatted date string
* @throws {TypeError} 1 argument required
* @throws {RangeError} `date` must not be Invalid Date
*
* @example
* // Represent 18 September 2019 in RFC 7231 format:
* const result = formatRFC7231(new Date(2019, 8, 18, 19, 0, 52))
* //=> 'Wed, 18 Sep 2019 19:00:52 GMT'
*/
export default function formatRFC7231(dirtyDate) {
if (arguments.length < 1) {
throw new TypeError(
`1 arguments required, but only ${arguments.length} present`
)
}
const originalDate = toDate(dirtyDate)
if (!isValid(originalDate)) {
throw new RangeError('Invalid time value')
}
const dayName = days[originalDate.getUTCDay()]
const dayOfMonth = addLeadingZeros(originalDate.getUTCDate(), 2)
const monthName = months[originalDate.getUTCMonth()]
const year = originalDate.getUTCFullYear()
const hour = addLeadingZeros(originalDate.getUTCHours(), 2)
const minute = addLeadingZeros(originalDate.getUTCMinutes(), 2)
const second = addLeadingZeros(originalDate.getUTCSeconds(), 2)
// Result variables.
return `${dayName}, ${dayOfMonth} ${monthName} ${year} ${hour}:${minute}:${second} GMT`
}