logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://anongit.hacktivis.me/git/pleroma-fe.git/

date_utils.js (2502B)


  1. export const SECOND = 1000
  2. export const MINUTE = 60 * SECOND
  3. export const HOUR = 60 * MINUTE
  4. export const DAY = 24 * HOUR
  5. export const WEEK = 7 * DAY
  6. export const MONTH = 30 * DAY
  7. export const YEAR = 365.25 * DAY
  8. export const relativeTimeMs = (date) => {
  9. if (typeof date === 'string') date = Date.parse(date)
  10. return Math.abs(Date.now() - date)
  11. }
  12. export const relativeTime = (date, nowThreshold = 1) => {
  13. const round = Date.now() > date ? Math.floor : Math.ceil
  14. const d = relativeTimeMs(date)
  15. const r = { num: round(d / YEAR), key: 'time.unit.years' }
  16. if (d < nowThreshold * SECOND) {
  17. r.num = 0
  18. r.key = 'time.now'
  19. } else if (d < MINUTE) {
  20. r.num = round(d / SECOND)
  21. r.key = 'time.unit.seconds'
  22. } else if (d < HOUR) {
  23. r.num = round(d / MINUTE)
  24. r.key = 'time.unit.minutes'
  25. } else if (d < DAY) {
  26. r.num = round(d / HOUR)
  27. r.key = 'time.unit.hours'
  28. } else if (d < WEEK) {
  29. r.num = round(d / DAY)
  30. r.key = 'time.unit.days'
  31. } else if (d < MONTH) {
  32. r.num = round(d / WEEK)
  33. r.key = 'time.unit.weeks'
  34. } else if (d < YEAR) {
  35. r.num = round(d / MONTH)
  36. r.key = 'time.unit.months'
  37. }
  38. return r
  39. }
  40. export const relativeTimeShort = (date, nowThreshold = 1) => {
  41. const r = relativeTime(date, nowThreshold)
  42. r.key += '_short'
  43. return r
  44. }
  45. export const unitToSeconds = (unit, amount) => {
  46. switch (unit) {
  47. case 'minutes': return 0.001 * amount * MINUTE
  48. case 'hours': return 0.001 * amount * HOUR
  49. case 'days': return 0.001 * amount * DAY
  50. }
  51. }
  52. export const secondsToUnit = (unit, amount) => {
  53. switch (unit) {
  54. case 'minutes': return (1000 * amount) / MINUTE
  55. case 'hours': return (1000 * amount) / HOUR
  56. case 'days': return (1000 * amount) / DAY
  57. }
  58. }
  59. export const isSameYear = (a, b) => {
  60. return a.getFullYear() === b.getFullYear()
  61. }
  62. export const isSameMonth = (a, b) => {
  63. return a.getFullYear() === b.getFullYear() &&
  64. a.getMonth() === b.getMonth()
  65. }
  66. export const isSameDay = (a, b) => {
  67. return a.getFullYear() === b.getFullYear() &&
  68. a.getMonth() === b.getMonth() &&
  69. a.getDate() === b.getDate()
  70. }
  71. export const durationStrToMs = (str) => {
  72. if (typeof str !== 'string') {
  73. return 0
  74. }
  75. const unit = str.replace(/[0-9,.]+/, '')
  76. const value = str.replace(/[^0-9,.]+/, '')
  77. switch (unit) {
  78. case 'd':
  79. return value * DAY
  80. case 'h':
  81. return value * HOUR
  82. case 'm':
  83. return value * MINUTE
  84. case 's':
  85. return value * SECOND
  86. default:
  87. return 0
  88. }
  89. }