Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript library for human-friendly relative date formatting [closed]

I'd like to display some dates as relative to the current date in a human-friendly format.

Examples of human-friendly relative dates:

  • 10 seconds ago
  • 20 minutes from now
  • 1 day ago
  • 5 weeks ago
  • 2 months ago

Basically faithfully preserving the highest order of magnitude (and by preference, only shifting up units when passing 2 of those units - 5 weeks instead of 1 month).

Though I could live with a library that had less control and even more friendly dates like:

  • yesterday
  • tomorrow
  • last week
  • a few minutes ago
  • in a couple hours

Any popular libraries for this?

like image 366
rampion Avatar asked Oct 03 '11 23:10

rampion


People also ask

What are the best JavaScript date formatting libraries?

Best overall: date-fns date-fns offers great documentation, functional architecture, and utilities that handle almost any task you can think of. If dates are a critical concern for your JavaScript application, use date-fns. Each feature has clear documentation written in ESM (ES Modules) for the browser.

What format is Date Now JavaScript?

now() The static Date. now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.


Video Answer


1 Answers

Since I wrote this answer, a well known library available is moment.js.


There are libraries available, but it is trivial to implement it yourself. Just use a handful of conditions.

Assume date is an instantiated Date object for the time you want to make a comparison against.

// Make a fuzzy time var delta = Math.round((+new Date - date) / 1000);  var minute = 60,     hour = minute * 60,     day = hour * 24,     week = day * 7;  var fuzzy;  if (delta < 30) {     fuzzy = 'just then.'; } else if (delta < minute) {     fuzzy = delta + ' seconds ago.'; } else if (delta < 2 * minute) {     fuzzy = 'a minute ago.' } else if (delta < hour) {     fuzzy = Math.floor(delta / minute) + ' minutes ago.'; } else if (Math.floor(delta / hour) == 1) {     fuzzy = '1 hour ago.' } else if (delta < day) {     fuzzy = Math.floor(delta / hour) + ' hours ago.'; } else if (delta < day * 2) {     fuzzy = 'yesterday'; } 

You would need to adapt this to handle future dates.

like image 59
alex Avatar answered Sep 23 '22 11:09

alex