aboutsummaryrefslogtreecommitdiff
path: root/src/services/date_utils/date_utils.js
blob: 69398c0cf38db4f4399fd90502523d054bcd8987 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
export const SECOND = 1000
export const MINUTE = 60 * SECOND
export const HOUR = 60 * MINUTE
export const DAY = 24 * HOUR
export const WEEK = 7 * DAY
export const MONTH = 30 * DAY
export const YEAR = 365.25 * DAY

export const relativeTimeMs = (date) => {
  if (typeof date === 'string') date = Date.parse(date)
  return Math.abs(Date.now() - date)
}
export const relativeTime = (date, nowThreshold = 1) => {
  const round = Date.now() > date ? Math.floor : Math.ceil
  const d = relativeTimeMs(date)
  const r = { num: round(d / YEAR), key: 'time.unit.years' }
  if (d < nowThreshold * SECOND) {
    r.num = 0
    r.key = 'time.now'
  } else if (d < MINUTE) {
    r.num = round(d / SECOND)
    r.key = 'time.unit.seconds'
  } else if (d < HOUR) {
    r.num = round(d / MINUTE)
    r.key = 'time.unit.minutes'
  } else if (d < DAY) {
    r.num = round(d / HOUR)
    r.key = 'time.unit.hours'
  } else if (d < WEEK) {
    r.num = round(d / DAY)
    r.key = 'time.unit.days'
  } else if (d < MONTH) {
    r.num = round(d / WEEK)
    r.key = 'time.unit.weeks'
  } else if (d < YEAR) {
    r.num = round(d / MONTH)
    r.key = 'time.unit.months'
  }
  return r
}

export const relativeTimeShort = (date, nowThreshold = 1) => {
  const r = relativeTime(date, nowThreshold)
  r.key += '_short'
  return r
}

export const unitToSeconds = (unit, amount) => {
  switch (unit) {
    case 'minutes': return 0.001 * amount * MINUTE
    case 'hours': return 0.001 * amount * HOUR
    case 'days': return 0.001 * amount * DAY
  }
}

export const secondsToUnit = (unit, amount) => {
  switch (unit) {
    case 'minutes': return (1000 * amount) / MINUTE
    case 'hours': return (1000 * amount) / HOUR
    case 'days': return (1000 * amount) / DAY
  }
}

export const isSameYear = (a, b) => {
  return a.getFullYear() === b.getFullYear()
}

export const isSameMonth = (a, b) => {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth()
}

export const isSameDay = (a, b) => {
  return a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
}

export const durationStrToMs = (str) => {
  if (typeof str !== 'string') {
    return 0
  }

  const unit = str.replace(/[0-9,.]+/, '')
  const value = str.replace(/[^0-9,.]+/, '')
  switch (unit) {
    case 'd':
      return value * DAY
    case 'h':
      return value * HOUR
    case 'm':
      return value * MINUTE
    case 's':
      return value * SECOND
    default:
      return 0
  }
}