Time.coffee 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. class Time
  2. since: (timestamp) ->
  3. now = +(new Date)/1000
  4. if timestamp > 1000000000000 # In ms
  5. timestamp = timestamp/1000
  6. secs = now - timestamp
  7. if secs < 60
  8. back = "Just now"
  9. else if secs < 60*60
  10. minutes = Math.round(secs/60)
  11. back = "" + minutes + " minutes ago"
  12. else if secs < 60*60*24
  13. back = "#{Math.round(secs/60/60)} hours ago"
  14. else if secs < 60*60*24*3
  15. back = "#{Math.round(secs/60/60/24)} days ago"
  16. else
  17. back = "on "+@date(timestamp)
  18. back = back.replace(/^1 ([a-z]+)s/, "1 $1") # 1 days ago fix
  19. return back
  20. dateIso: (timestamp=null) ->
  21. if not timestamp
  22. timestamp = window.Time.timestamp()
  23. if timestamp > 1000000000000 # In ms
  24. timestamp = timestamp/1000
  25. tzoffset = (new Date()).getTimezoneOffset() * 60
  26. return (new Date((timestamp - tzoffset) * 1000)).toISOString().split("T")[0]
  27. date: (timestamp=null, format="short") ->
  28. if not timestamp
  29. timestamp = window.Time.timestamp()
  30. if timestamp > 1000000000000 # In ms
  31. timestamp = timestamp/1000
  32. parts = (new Date(timestamp * 1000)).toString().split(" ")
  33. if format == "short"
  34. display = parts.slice(1, 4)
  35. else if format == "day"
  36. display = parts.slice(1, 3)
  37. else if format == "month"
  38. display = [parts[1], parts[3]]
  39. else if format == "long"
  40. display = parts.slice(1, 5)
  41. return display.join(" ").replace(/( [0-9]{4})/, ",$1")
  42. weekDay: (timestamp) ->
  43. if timestamp > 1000000000000 # In ms
  44. timestamp = timestamp/1000
  45. return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][ (new Date(timestamp * 1000)).getDay() ]
  46. timestamp: (date="") ->
  47. if date == "now" or date == ""
  48. return parseInt(+(new Date)/1000)
  49. else
  50. return parseInt(Date.parse(date)/1000)
  51. window.Time = new Time