29

I use moment(d, "YYYYMMDD").fromNow(); to get diff between date now and some date, but I would like to get without string "a few days ago".

Instead, I would like to get "7d" (7m, 1s, etc).

How can I do this?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Vahe Akhsakhalyan
  • 2,140
  • 3
  • 24
  • 38

3 Answers3

43

If you want just to get the difference between two dates instead of a relative string just use the diff function.

var date  = moment("20170101", "YYYYMMDD");
var date7 = moment("20170108", "YYYYMMDD");
var mins7 = moment("20170101 00:07", "YYYYMMDD HH:mm");
var secs1 = moment("20170101 00:00:01", "YYYYMMDD HH:mm:ss");

console.log(date7.diff(date, "days")    + "d"); // "7d"
console.log(mins7.diff(date, "minutes") + "m"); // "7m"
console.log(secs1.diff(date, "seconds") + "s"); // "1s"
codersl
  • 2,222
  • 4
  • 30
  • 33
18

Moment.diff does exactly that.

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

You can specify a unit:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1
Brother Woodrow
  • 6,092
  • 3
  • 18
  • 20
  • Beautiful. If you read `.diff(` as a minus sign `-`, you also know whether a negative or a positive number comes out. – qräbnö Dec 30 '20 at 17:25
12

var before = moment('2017.02.12 09:00','YYYY.MM.DD HH:mm');
var now = moment();

console.log(
  moment(now - before)
  .format('D[ day(s)] H[ hour(s)] m[ minute(s)] s[ second(s) ago.]')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Bulent Vural
  • 2,630
  • 1
  • 13
  • 18