Search code examples
javascriptdatemomentjsformatdatetime

How to format dates with momentjs like SO?


StackOwerflow formates post's create time like the following:

asked 58 secs ago
asked 1 min ago 
asked 13 hours ago
asked yesterday
asked 2 days ago
asked Jun 22 at 11:13

I want to make something like this with my momentjs. What format string should I use to achieve this?


Solution

  • Assuming you have a date saved in a variable, for example myDate, this task is very simple with 'momentJS'.

    If myDate is in YYYYMMDD format simply call the 'momentJS' fromNow function like so:

    moment(myDate, "YYYYMMDD").fromNow();
    

    Please reference this section of the 'momentJS' docs for further details. I highly recommend reading through the docs of the library you're attempting to use before posting questions to StackOverflow as well. If you're still stumped after reading through the docs then posting here is a great next option :)

    Note: If you want to tweak the 'momentJS' fromNow function you could add a custom fromNowCustom function with something like this:

    moment.fn.fromNowCustom = function(a) {
      if (/*whatever scenario you're customizing for*/) {
        return /*custom output*/;
      } else {
        return this.fromNow(a);
      }
    };
    

    ...then reference it like so:

    moment(myDate, "YYYYMMDD").fromNowCustom();