1

I have a JSON formatted date, say: 2017-08-01T23:28:56.782Z I've given it fromNow() to display a relative date a month ago.

Is there a way to format it to display something like 30d?

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33
  • See [here](https://stackoverflow.com/q/42216583/4131048) and [here](https://stackoverflow.com/a/41515757/4131048) – VincenzoC Sep 07 '17 at 13:15
  • Possible duplicate of [Count days until today moment.js](https://stackoverflow.com/questions/16424702/count-days-until-today-moment-js) – Joseph Cho Sep 07 '17 at 14:24

3 Answers3

4

You can use relativeTimeThreshold to customize thresholds for moment relative time. In your case, you can update the d property that represents:

least number of days to be considered a month.

If you want to show d instead of days, you can use customize relativeTime property with the updateLocale method.

If you want to remove the suffix (e.g. in / ago) from fromNow output, you can simply use fromNow(true).

Here a working sample:

var m = moment('2017-08-01T23:28:56.782Z');
console.log(m.fromNow());

moment.relativeTimeThreshold('d', 30*12);
moment.updateLocale('en', {
  relativeTime : {
    dd: "%dd",
  }
});

console.log(m.fromNow(true));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112
3

1 . %d will print no of digits .
2. " " will show Sting Literal . eg : Sec, s , d, y, w .

OUTPUT : 1d , 1w , 1y,

const TIME_ZONE = -1 * new Date().getTimezoneOffset() / 60;

 this.getDateFrom("2018-02-22 14:27:56");

 getDateFrom(givenDate) {
    return moment(givenDate)
      .add(TIME_ZONE, "hours")
      .fromNow(
        updateLocale("en", {
          relativeTime: {
            future: "in %s",
            past: "%s ",
            s: "sec",
            m: "%d m",
            mm: "%d m",
            h: "%d h",
            hh: "%d h",
            d: "%d d",
            dd: "%d d",
            M: "a mth",
            MM: "%d mths",
            y: "y",
            yy: "%d y"
          }
        })
      );
  }

OTHER WAY .

fromNow(true) : true will trim your format (1 week ago) .

return moment(givenDate)
      .add(TIME_ZONE, "hours")
      .fromNow(true);

OUTPUT : a day , 1 week , 1 year,

Syed Zain Ali
  • 1,206
  • 1
  • 14
  • 20
1

I think I might be a bit out of date since there are 36 days from your target date.

var a = moment(); // today
var b = moment("2017-08-01T23:28:56.782Z"); // target date
var diffInDays = a.diff(b, 'days') + 'd'; // 36d;

The above code gets your days from the specified target date.

Joseph Cho
  • 4,033
  • 4
  • 26
  • 33