|
- type FormatDate = (d: Date) => string
-
- export const formatDate: FormatDate = d => {
- const yearRaw = d.getFullYear()
- const monthRaw = d.getMonth() + 1
- const dateRaw = d.getDate()
- const hourRaw = d.getHours()
- const minuteRaw = d.getMinutes()
- const year = yearRaw.toString().padStart(4, '0')
- const month = monthRaw.toString().padStart(2, '0')
- const date = dateRaw.toString().padStart(2, '0')
- const hour = hourRaw.toString().padStart(2, '0')
- const minute = minuteRaw.toString().padStart(2, '0')
-
- return `${year}-${month}-${date} ${hour}:${minute}`
- }
-
- export enum TimeDivision {
- MILLISECONDS,
- SECONDS,
- MINUTES,
- HOURS,
- DAYS
- }
-
- type GetTimeDifference = (a: Date, b: Date) => (c: TimeDivision) => number
-
- export const getTimeDifference: GetTimeDifference = (a, b) => {
- const ms = b.getTime() - a.getTime()
- const absoluteMs = ms < 0 ? -ms : ms
-
- return c => {
- let divisionDifference = absoluteMs
- if (c === TimeDivision.MILLISECONDS) {
- return divisionDifference
- }
-
- divisionDifference /= 1000
- if (c === TimeDivision.SECONDS) {
- return divisionDifference
- }
-
- divisionDifference /= 60
- if (c === TimeDivision.MINUTES) {
- return divisionDifference
- }
-
- divisionDifference /= 60
- if (c === TimeDivision.HOURS) {
- return divisionDifference
- }
-
- divisionDifference /= 24
- if (c === TimeDivision.DAYS) {
- return divisionDifference
- }
-
- throw new Error('Unknown time division.')
- }
- }
-
- type AddTime = (refDate: Date, increment: number) => (c: TimeDivision) => Date
-
- export const addTime: AddTime = (refDate, increment) => {
- const futureDate = new Date(refDate.getTime())
- return c => {
- let msIncrement = increment
- if (c === TimeDivision.MILLISECONDS) {
- futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
- return futureDate
- }
-
- msIncrement *= 1000
- if (c === TimeDivision.SECONDS) {
- futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
- return futureDate
- }
-
- msIncrement *= 60
- if (c === TimeDivision.MINUTES) {
- futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
- return futureDate
- }
-
- msIncrement *= 60
- if (c === TimeDivision.HOURS) {
- futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
- return futureDate
- }
-
- msIncrement *= 24
- if (c === TimeDivision.DAYS) {
- futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
- return futureDate
- }
- throw new Error('Unknown time division.')
- }
- }
|