Browser extension that demonstrates the Web Annotation Discovery mechanism: subscribe to people’s annotation collections/‘feeds’, to see their notes on the web; and create & publish annotations yourself.

web-annotation-discovery-we.../src/util/ niceTime.ts
53 lines
2.2 KiB

  1. function hourString(date: Date) {
  2. // return date.toLocaleTimeString([], {hour: 'numeric', minute: '2-digit'})
  3. return `${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}`
  4. }
  5. function dayString(date: Date) {
  6. const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  7. return days[date.getDay()]
  8. }
  9. function monthString(date: Date) {
  10. const months = ['Jan', 'Feb', 'March', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec']
  11. return months[date.getMonth()]
  12. }
  13. // Get something nicely readable - at least to my personal taste.
  14. export default function niceTime(date: Date, { now = undefined }: { now?: Date } = {}) {
  15. const then = new Date(date)
  16. now = now || new Date()
  17. const secondsAgo = (+now - +then) / 1000
  18. if (secondsAgo < -60 * 60 * 24) {
  19. return 'in the future?!'
  20. }
  21. if (secondsAgo < -60) {
  22. return 'soon?!'
  23. }
  24. if (secondsAgo < 2) { return 'now' }
  25. if (secondsAgo < 60) { return `seconds ago` }
  26. // if (secondsAgo < 60) { return `${Math.round(secondsAgo)} seconds ago` }
  27. if (secondsAgo < 120) { return 'a minute ago' }
  28. if (secondsAgo < 60 * 10) { return `${Math.round(secondsAgo / 60)} minutes ago` }
  29. if (secondsAgo < 60 * 60) { return `${Math.round(secondsAgo / 60 / 5) * 5} minutes ago` }
  30. if (secondsAgo < 60 * 60 * 24
  31. && (now.getDay() === then.getDay() || secondsAgo < 60 * 60 * 6)) { return hourString(then) }
  32. if (secondsAgo < 60 * 60 * 24) { return `Yesterday ${hourString(then)}` }
  33. if (secondsAgo < 60 * 60 * 24 * 3) { return `${dayString(then)} ${hourString(then)}` }
  34. if (then.getFullYear() === now.getFullYear()) { return `${then.getDate()} ${monthString(then)}` }
  35. return `${then.getDate()} ${monthString(then)} ${then.getFullYear()}`
  36. }
  37. export function niceDate(date: Date, { now = new Date() } = {}) {
  38. const then = new Date(date)
  39. if (then.getFullYear() !== now.getFullYear()) {
  40. return `${then.getDate()} ${monthString(then)} ${then.getFullYear()}`
  41. }
  42. if (then.getMonth() === now.getMonth()) {
  43. const daysAgo = now.getDate() - then.getDate()
  44. if (daysAgo === 0) return `Today`
  45. if (daysAgo === 1) return `Yesterday`
  46. }
  47. return `${dayString(then)} ${then.getDate()} ${monthString(then)}`
  48. }