Skip to content

Instantly share code, notes, and snippets.

@davidrleonard
Last active February 18, 2024 11:23
Show Gist options
  • Save davidrleonard/259fe449b1ec13bf7d87cde567ca0fde to your computer and use it in GitHub Desktop.
Save davidrleonard/259fe449b1ec13bf7d87cde567ca0fde to your computer and use it in GitHub Desktop.
moment.fromNow() implemented in vanilla JavaScript as a simple, standalone function. Runs in the browser. No dependencies required.
/**
* Implements all the behaviors of moment.fromNow(). Pass a
* valid JavaScript Date object and the method will return the
* time that has passed since that date in a human-readable
* format. Passes the moment test suite for `fromNow()`.
* See: https://momentjs.com/docs/#/displaying/fromnow/
*
* @example
*
* var pastDate = new Date('2017-10-01T02:30');
* var message = fromNow(pastDate);
* //=> '2 days ago'
*
* @license
*
* Copyright 2023 David Leonard
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @param {Date} Native JavaScript Date object
* @return {string}
*/
function fromNow(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var years = Math.floor(seconds / 31536000);
var months = Math.floor(seconds / 2592000);
var days = Math.floor(seconds / 86400);
if (days > 548) {
return years + " years ago";
}
if (days >= 320 && days <= 547) {
return "a year ago";
}
if (days >= 45 && days <= 319) {
return months + " months ago";
}
if (days >= 26 && days <= 45) {
return "a month ago";
}
var hours = Math.floor(seconds / 3600);
if (hours >= 36 && days <= 25) {
return days + " days ago";
}
if (hours >= 22 && hours <= 35) {
return "a day ago";
}
var minutes = Math.floor(seconds / 60);
if (minutes >= 90 && hours <= 21) {
return hours + " hours ago";
}
if (minutes >= 45 && minutes <= 89) {
return "an hour ago";
}
if (seconds >= 90 && minutes <= 44) {
return minutes + " minutes ago";
}
if (seconds >= 45 && seconds <= 89) {
return "a minute ago";
}
if (seconds >= 0 && seconds <= 45) {
return "a few seconds ago";
}
}
/*
* Test suite copied from moment.js on 11/13/17 to validate method against.
* Requires `moment` to run the test (used to construct the dates).
* See tests here: https://github.com/moment/moment/blob/ed1fc742b179708d0a987a639979178616309f93/src/test/moment/relative_time.js#L7-L41
*
* @license
*
* Copyright 2023 David Leonard
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var moment = require('moment');
var assert = require('assert');
var a = moment();
// Seconds to minutes threshold
a.subtract(44, 'seconds');
assert.equal(timeSince( a.toDate() ), 'a few seconds ago', 'Below default seconds to minutes threshold');
a.subtract(1, 'seconds');
assert.equal(timeSince( a.toDate() ), 'a minute ago', 'Above default seconds to minutes threshold');
// Minutes to hours threshold
a = moment();
a.subtract(44, 'minutes');
assert.equal(timeSince( a.toDate() ), '44 minutes ago', 'Below default minute to hour threshold');
a.subtract(1, 'minutes');
assert.equal(timeSince( a.toDate() ), 'an hour ago', 'Above default minute to hour threshold');
// Hours to days threshold
a = moment();
a.subtract(21, 'hours');
assert.equal(timeSince( a.toDate() ), '21 hours ago', 'Below default hours to day threshold');
a.subtract(1, 'hours');
assert.equal(timeSince( a.toDate() ), 'a day ago', 'Above default hours to day threshold');
// Days to month threshold
a = moment();
a.subtract(25, 'days');
assert.equal(timeSince( a.toDate() ), '25 days ago', 'Below default days to month (singular) threshold');
a.subtract(1, 'days');
assert.equal(timeSince( a.toDate() ), 'a month ago', 'Above default days to month (singular) threshold');
// months to year threshold
a = moment();
a.subtract(10, 'months');
assert.equal(timeSince( a.toDate() ), '10 months ago', 'Below default days to years threshold');
a.subtract(1, 'month');
assert.equal(timeSince( a.toDate() ), 'a year ago', 'Above default days to years threshold');
@kospl
Copy link

kospl commented Feb 13, 2021

I have the following issue:
When I passed a date in the function I received the following output:

  1. seconds: 4668503, months: 1 and days: 54
  2. Output: 1 months ago. Is that expected behavior?

Changing from using Math.floor to Math.round should help, see https://github.com/moment/moment/blob/b7ec8e2ec068e03de4f832f28362675bb9e02261/dist/moment.js#L5399

@GrahamBorland
Copy link

GrahamBorland commented Feb 7, 2023

Hey! Thanks for providing this.

@davidrleonard Is there a license under which we can use it?

@rambii
Copy link

rambii commented Jul 27, 2023

Wanted to note that there is also a native RelativeTimeFormat function which I found helpful.
Doesn't include the averaging (like a minute ago) that you do here and I find very elegant but works for concrete values.

new Intl.RelativeTimeFormat().format(-4, 'day');
// => "4 days ago"

https://github.com/you-dont-need/You-Dont-Need-Momentjs#time-from-now

@davidrleonard
Copy link
Author

@GrahamBorland Updated code to indicate it is released under the MIT license

@necodeus
Copy link

It actually doesn't implement all the behaviors of moment.fromNow() 🥲

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment