Monorepo containing core modules of Zeichen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.5 KiB

  1. type FormatDate = (d: Date) => string
  2. export const formatDate: FormatDate = d => {
  3. const yearRaw = d.getFullYear()
  4. const monthRaw = d.getMonth() + 1
  5. const dateRaw = d.getDate()
  6. const hourRaw = d.getHours()
  7. const minuteRaw = d.getMinutes()
  8. const year = yearRaw.toString().padStart(4, '0')
  9. const month = monthRaw.toString().padStart(2, '0')
  10. const date = dateRaw.toString().padStart(2, '0')
  11. const hour = hourRaw.toString().padStart(2, '0')
  12. const minute = minuteRaw.toString().padStart(2, '0')
  13. return `${year}-${month}-${date} ${hour}:${minute}`
  14. }
  15. export enum TimeDivision {
  16. MILLISECONDS,
  17. SECONDS,
  18. MINUTES,
  19. HOURS,
  20. DAYS
  21. }
  22. type GetTimeDifference = (a: Date, b: Date) => (c: TimeDivision) => number
  23. export const getTimeDifference: GetTimeDifference = (a, b) => {
  24. const ms = b.getTime() - a.getTime()
  25. const absoluteMs = ms < 0 ? -ms : ms
  26. return c => {
  27. let divisionDifference = absoluteMs
  28. if (c === TimeDivision.MILLISECONDS) {
  29. return divisionDifference
  30. }
  31. divisionDifference /= 1000
  32. if (c === TimeDivision.SECONDS) {
  33. return divisionDifference
  34. }
  35. divisionDifference /= 60
  36. if (c === TimeDivision.MINUTES) {
  37. return divisionDifference
  38. }
  39. divisionDifference /= 60
  40. if (c === TimeDivision.HOURS) {
  41. return divisionDifference
  42. }
  43. divisionDifference /= 24
  44. if (c === TimeDivision.DAYS) {
  45. return divisionDifference
  46. }
  47. throw new Error('Unknown time division.')
  48. }
  49. }
  50. type AddTime = (refDate: Date, increment: number) => (c: TimeDivision) => Date
  51. export const addTime: AddTime = (refDate, increment) => {
  52. const futureDate = new Date(refDate.getTime())
  53. return c => {
  54. let msIncrement = increment
  55. if (c === TimeDivision.MILLISECONDS) {
  56. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  57. return futureDate
  58. }
  59. msIncrement *= 1000
  60. if (c === TimeDivision.SECONDS) {
  61. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  62. return futureDate
  63. }
  64. msIncrement *= 60
  65. if (c === TimeDivision.MINUTES) {
  66. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  67. return futureDate
  68. }
  69. msIncrement *= 60
  70. if (c === TimeDivision.HOURS) {
  71. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  72. return futureDate
  73. }
  74. msIncrement *= 24
  75. if (c === TimeDivision.DAYS) {
  76. futureDate.setMilliseconds(futureDate.getMilliseconds() + msIncrement)
  77. return futureDate
  78. }
  79. throw new Error('Unknown time division.')
  80. }
  81. }