import toDate from '../toDate/index' ; import type { FormatOptions , RepresentationOptions } from '../types' ; import addLeadingZeros from '../_lib/addLeadingZeros/index' ; import requiredArgs from '../_lib/requiredArgs' ; name category summary description param { Date | Number } date param options param { 'extended' | 'basic' } options . format param { 'complete' | 'date' | 'time' } options . representation returns { String } throws throws throws throws example example example example export default function formatISO ( date , options ? ) { requiredArgs ( 1 , arguments ) ; const originalDate = toDate ( date ) ; if ( isNaN ( originalDate . getTime ( ) ) ) { throw new RangeError ( 'Invalid time value' ) ; } const format = ! options ?. format ? 'extended' : String ( options . format ) ; const representation = ! options ?. representation ? 'complete' : String ( options . representation ) ; if ( format !== 'extended' && format !== 'basic' ) { throw new RangeError ( "format must be 'extended' or 'basic'" ) ; } if ( representation !== 'date' && representation !== 'time' && representation !== 'complete' ) { throw new RangeError ( "representation must be 'date', 'time', or 'complete'" ) ; } let result = '' ; let tzOffset = '' ; const dateDelimiter = format === 'extended' ? '-' : '' ; const timeDelimiter = format === 'extended' ? ':' : '' ; if ( representation !== 'time' ) { const day = addLeadingZeros ( originalDate . getDate ( ) , 2 ) ; const month = addLeadingZeros ( originalDate . getMonth ( ) + 1 , 2 ) ; const year = addLeadingZeros ( originalDate . getFullYear ( ) , 4 ) ; result = `${ year }${ dateDelimiter }${ month }${ dateDelimiter }${ day }` ; } if ( representation !== 'date' ) { const offset = originalDate . getTimezoneOffset ( ) ; if ( offset !== 0 ) { const absoluteOffset = Math . abs ( offset ) ; const hourOffset = addLeadingZeros ( Math . floor ( absoluteOffset / 60 ) , 2 ) ; const minuteOffset = addLeadingZeros ( absoluteOffset % 60 , 2 ) ; const sign = offset < 0 ? '+' : '-' ; tzOffset = `${ sign }${ hourOffset }:${ minuteOffset }` ; } else { tzOffset = 'Z' ; } const hour = addLeadingZeros ( originalDate . getHours ( ) , 2 ) ; const minute = addLeadingZeros ( originalDate . getMinutes ( ) , 2 ) ; const second = addLeadingZeros ( originalDate . getSeconds ( ) , 2 ) ; const separator = result === '' ? '' : 'T' ; const time = [ hour , minute , second ] . join ( timeDelimiter ) ; result = `${ result }${ separator }${ time }${ tzOffset }` ; } return result ; }