0

I am using momentjs in an angular app and I don't have any code to show here. I tried to play around with it and try to figure it out but ended up in a mess.

What I want to happen is I have a createdAt property that I am retrieving to some API server and I want to display it like the facebook way for displaying time relative in the post but in a nicer way.

For example:

if within this day display relative time

  1. A few seconds ago.
  2. A minute ago
  3. 2 minutes ago (if more than 1 minute)
  4. An hour ago (if 1 hour ago)
  5. 2 hours ago (if more than 1 hour until 24 hours ago)
  6. Yesterday at 10:03 am (If 1 day after)
  7. Last Tuesday at 7:30 pm (After 48 hours)
  8. Last month at June 18 on 7:30 pm (After a month)

and the list goes on for year.

I know I can do this using multiple conditions but ended up messing it. Is there a better way to do this?

Can someone shed some light for me?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
KnowledgeSeeker
  • 1,058
  • 2
  • 19
  • 44
  • 1
    Did you try using [`moment.fromNow()`](https://momentjs.com/docs/#/displaying/fromnow/)?. Is not exact same output for all your cases but is close – charlietfl Jul 19 '18 at 02:28
  • @charlietfl yes I have used that. But the problem is when for example I posted some content yesterday and it displays 1 day ago that should be **yesterday at time** instead of 1 day ago. So I am going to use multiple conditions to achieve that right? – KnowledgeSeeker Jul 19 '18 at 02:40
  • 1
    Probably yes to get less generic. You probably only need several variations though that are different than the defaults ... such as checking if it is in the last week or last month – charlietfl Jul 19 '18 at 02:43
  • I try to do it and I would ask some help if something goes wrong. Thanks! @charlietfl – KnowledgeSeeker Jul 19 '18 at 03:30
  • That would be best. Nobody is going to write all the conditions for you but if you get started and then have actual code will get lots of help sorting out issues. Just make sure to provide sample inputs to make it easier to get that help also – charlietfl Jul 19 '18 at 03:33
  • Possible duplicate of [How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites](https://stackoverflow.com/questions/3177836/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-site) – Liam Jul 19 '18 at 12:13

0 Answers0