0

This should be easy... but I've had no luck scouring the docs!

How do I get Moment.js to return: 15 minutes

In order to get 15 minutes ago I can write:

moment().subtract(15, 'minutes').fromNow()

Which command should I use to get just 15 minutes?

Ed Williams
  • 2,447
  • 3
  • 15
  • 21
  • Possible duplicate of [How do I use format() on a moment.js duration?](http://stackoverflow.com/questions/13262621/how-do-i-use-format-on-a-moment-js-duration) – Just a student Mar 20 '17 at 15:50

2 Answers2

2

If you want to explicitly remove the "ago" or similar phrasing, simply pass true to your fromNow() function as detailed in the documentation:

moment().subtract(15, 'minutes').fromNow(true);

Example

console.log(moment([2007, 0, 29]).fromNow());     // "10 years ago"
console.log(moment([2007, 0, 29]).fromNow(true)); // "10 years"
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • Excellent, thank you! If you fancy another challenge... `Moment().subtract(1, 'hour').fromNow(true)` returns `an hour`. Can it be made to say `1 hour`? – Ed Williams Mar 20 '17 at 15:57
  • If you want to adjust these, you can make changes to [the relative time locale settings](https://momentjs.com/docs/#/customization/relative-time/), which allow you to define which phrases you want to use, etc. So you could replace "an hour" with "1 hour". – Rion Williams Mar 20 '17 at 16:17
1

You can use moment durations.

Duration from the difference between two dates:

var now = moment();
var then = moment().subtract(15, 'minutes');
moment.duration(now.diff(then)).humanize();

15 minutes

Duration without using dates:

moment.duration(15, 'minutes').humanize();

15 minutes

Justin Hellreich
  • 575
  • 5
  • 15