(
date: DateArg<Date> & {},
options?: FormatRFC3339Options,
)
| 39 | * //=> '2019-09-18T19:00:52.234Z' |
| 40 | */ |
| 41 | export function formatRFC3339( |
| 42 | date: DateArg<Date> & {}, |
| 43 | options?: FormatRFC3339Options, |
| 44 | ): string { |
| 45 | const date_ = toDate(date, options?.in); |
| 46 | |
| 47 | if (!isValid(date_)) { |
| 48 | throw new RangeError("Invalid time value"); |
| 49 | } |
| 50 | |
| 51 | const fractionDigits = options?.fractionDigits ?? 0; |
| 52 | |
| 53 | const day = addLeadingZeros(date_.getDate(), 2); |
| 54 | const month = addLeadingZeros(date_.getMonth() + 1, 2); |
| 55 | const year = date_.getFullYear(); |
| 56 | |
| 57 | const hour = addLeadingZeros(date_.getHours(), 2); |
| 58 | const minute = addLeadingZeros(date_.getMinutes(), 2); |
| 59 | const second = addLeadingZeros(date_.getSeconds(), 2); |
| 60 | |
| 61 | let fractionalSecond = ""; |
| 62 | if (fractionDigits > 0) { |
| 63 | const milliseconds = date_.getMilliseconds(); |
| 64 | const fractionalSeconds = Math.trunc( |
| 65 | milliseconds * Math.pow(10, fractionDigits - 3), |
| 66 | ); |
| 67 | fractionalSecond = "." + addLeadingZeros(fractionalSeconds, fractionDigits); |
| 68 | } |
| 69 | |
| 70 | let offset = ""; |
| 71 | const tzOffset = date_.getTimezoneOffset(); |
| 72 | |
| 73 | if (tzOffset !== 0) { |
| 74 | const absoluteOffset = Math.abs(tzOffset); |
| 75 | const hourOffset = addLeadingZeros(Math.trunc(absoluteOffset / 60), 2); |
| 76 | const minuteOffset = addLeadingZeros(absoluteOffset % 60, 2); |
| 77 | // If less than 0, the sign is +, because it is ahead of time. |
| 78 | const sign = tzOffset < 0 ? "+" : "-"; |
| 79 | |
| 80 | offset = `${sign}${hourOffset}:${minuteOffset}`; |
| 81 | } else { |
| 82 | offset = "Z"; |
| 83 | } |
| 84 | |
| 85 | return `${year}-${month}-${day}T${hour}:${minute}:${second}${fractionalSecond}${offset}`; |
| 86 | } |
no test coverage detected