本文介绍了Javascript库,用于人性化的相对日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以人性化的格式显示与当前日期相对的某些日期。

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秒前

  • 20分钟以前

  • 1天前

  • 5周前

  • 2个月前

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

基本上忠实地保留了最高的数量级(并且优先考虑,只有在通过其中2个时移动单位单位 - 5周,而不是1个月)。

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

任何流行的图书馆?

推荐答案

自从我写了这个答案之后,最好的图书馆是。

Since I wrote this answer, the best 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.

这篇关于Javascript库,用于人性化的相对日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:22