aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/app/helpers/utils/date.ts
blob: 75363cc8197d78440498e151838398b9b4f4eb24 (plain) (blame)
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
import { DatePipe } from '@angular/common'

let datePipe: DatePipe
let intl: Intl.DateTimeFormat

type DateFormat = 'medium' | 'precise'

function dateToHuman (localeId: string, date: Date, format: 'medium' | 'precise' = 'medium') {
  if (!datePipe) {
    datePipe = new DatePipe(localeId)
  }

  if (!intl) {
    intl = new Intl.DateTimeFormat(localeId, {
      hour: 'numeric',
      minute: 'numeric',
      second: 'numeric',
      year: '2-digit',
      month: 'numeric',
      day: 'numeric',
      fractionalSecondDigits: 3
    })
  }

  if (format === 'medium') return datePipe.transform(date, format)
  if (format === 'precise') return intl.format(date)
}

function durationToString (duration: number) {
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = duration % 60

  const minutesPadding = minutes >= 10 ? '' : '0'
  const secondsPadding = seconds >= 10 ? '' : '0'
  const displayedHours = hours > 0 ? hours.toString() + ':' : ''

  return (
    displayedHours + minutesPadding + minutes.toString() + ':' + secondsPadding + seconds.toString()
  ).replace(/^0/, '')
}

export {
  DateFormat,

  durationToString,
  dateToHuman
}