用于人性化相对日期格式的 Javascript 库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7641791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:01:27  来源:igfitidea点击:

Javascript library for human-friendly relative date formatting

javascriptdateformatting

提问by rampion

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
  • 10 秒前
  • 20 分钟后
  • 1天前
  • 5 周前
  • 2个月前

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).

基本上忠实地保持最高数量级(并且优先选择,仅在超过其中 2 个单位时才转移单位 - 5 周而不是 1 个月)。

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?

任何流行的图书馆?

采纳答案by alex

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

由于我写了这个答案,一个众所周知的可用库是moment.js



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

可用,但自己实现它是微不足道的。只需使用一些条件。

Assume dateis an instantiated Dateobject for the time you want to make a comparison against.

假设dateDate您要进行比较的时间的实例化对象。

// 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.

您需要对此进行调整以处理未来的日期。

回答by timrwood

I wrote moment.js, a date library that does this. It's about 5KB (2011)52KB (2019), and works in browsers and in Node. It's also probably the most popular and famous date library for JavaScript.

我写了moment.js,这是一个执行此操作的日期库。它大约5KB (2011)52KB (2019),适用于浏览器和 Node.js。它也可能是最流行和最著名的 JavaScript 日期库。

It supports timeago, formatting, parsing, querying, manipulating, i18n, etc.

支持timeago、格式化、解析、查询、操作、i18n等。

Timeago (relative time) for dates in the past is done with moment().fromNow(). For example, to display January 1, 2019 in the timeago format:

过去日期的 Timeago(相对时间)使用moment().fromNow(). 例如,要以 timeago 格式显示 2019 年 1 月 1 日:

let date = moment("2019-01-01", "YYYY-MM-DD");
console.log(date.fromNow());
<script src="https://momentjs.com/downloads/moment.min.js"></script>

The timeago strings are customizable with moment.updateLocale(), so you can change them how you see fit.

timeago 字符串可使用 进行自定义moment.updateLocale(),因此您可以根据自己的喜好更改它们。

The cutoffs are not what the question requests ("5 weeks" vs. "1 month"), but it is documented as to which strings are used for what time range.

截止时间不是问题要求的(“5 周”与“1 个月”),但它记录了哪些字符串用于什么时间范围。

回答by Hendy Irawan

sugar.jshas great date formatting functions.

Sugar.js有很棒的日期格式化功能。

Not only that, it also provides common general purpose functions like string formatting, number formatting, etc. that are convenient to use.

不仅如此,它还提供了常用的通用功能,如字符串格式化、数字格式化等,方便使用。

回答by Hari Pachuveetil

Here's something from the John Resig - http://ejohn.org/blog/javascript-pretty-date/

这是 John Resig 的一些内容 - http://ejohn.org/blog/javascript-pretty-date/

EDIT (6/27/2014): Following up on the comment from Sumurai8- though the linked page still works, here is the excerpt for the pretty.jslinked to from the article above:

编辑(2014年 6月 27 日):跟进Sumurai8的评论- 尽管链接页面仍然有效,以下是pretty.js上述文章链接的摘录:

pretty.js

漂亮的.js

/*
 * JavaScript Pretty Date
 * Copyright (c) 2011 John Resig (ejohn.org)
 * Licensed under the MIT and GPL licenses.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time) {
    var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);

    if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) return;

    return day_diff == 0 && (
    diff < 60 && "just now" || diff < 120 && "1 minute ago" || diff < 3600 && Math.floor(diff / 60) + " minutes ago" || diff < 7200 && "1 hour ago" || diff < 86400 && Math.floor(diff / 3600) + " hours ago") || day_diff == 1 && "Yesterday" || day_diff < 7 && day_diff + " days ago" || day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if (typeof jQuery != "undefined") jQuery.fn.prettyDate = function() {
    return this.each(function() {
        var date = prettyDate(this.title);
        if (date) jQuery(this).text(date);
    });
};

Usage:

用法:

prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined

Excerpt from the article on usage:

摘自关于用法的文章:

Example Usage

In the following examples I make all the anchors on the site, that have a title with a date in it, have a pretty date as their inner text. Additionally, I continue to update the links every 5 seconds after the page has loaded.

示例用法

在下面的例子中,我制作了网站上所有带有日期的标题的锚点,将一个漂亮的日期作为它们的内部文本。此外,我会在页面加载后每 5 秒继续更新链接。

With JavaScript:

使用 JavaScript:

function prettyLinks(){
    var links = document.getElementsByTagName("a");
    for ( var i = 0; i < links.length; i++ )
        if ( links[i].title ) {
            var date = prettyDate(links[i].title);
            if ( date )
                links[i].innerHTML = date;
        }
}
prettyLinks();
setInterval(prettyLinks, 5000);

With jQuery:

使用 jQuery:

$("a").prettyDate();
setInterval(function(){ $("a").prettyDate(); }, 5000);


Faiz: Made some changes to the original code, bug fixes and improvements.

Faiz:对原始代码进行了一些更改、错误修复和改进。

function prettyDate(time) {
    var date = new Date((time || "").replace(/-/g, "/").replace(/[TZ]/g, " ")),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        day_diff = Math.floor(diff / 86400);
    var year = date.getFullYear(),
        month = date.getMonth()+1,
        day = date.getDate();

    if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31)
        return (
            year.toString()+'-'
            +((month<10) ? '0'+month.toString() : month.toString())+'-'
            +((day<10) ? '0'+day.toString() : day.toString())
        );

    var r =
    ( 
        (
            day_diff == 0 && 
            (
                (diff < 60 && "just now")
                || (diff < 120 && "1 minute ago")
                || (diff < 3600 && Math.floor(diff / 60) + " minutes ago")
                || (diff < 7200 && "1 hour ago")
                || (diff < 86400 && Math.floor(diff / 3600) + " hours ago")
            )
        )
        || (day_diff == 1 && "Yesterday")
        || (day_diff < 7 && day_diff + " days ago")
        || (day_diff < 31 && Math.ceil(day_diff / 7) + " weeks ago")
    );
    return r;
}

回答by citykid

here an example of sugar vs moment: for a calendar that displays weeks, I needed the last monday value:

这是糖与时刻的示例:对于显示周的日历,我需要最后一个星期一的值:

moment.js

时刻.js

var m = moment().subtract("days", 1).sod().day(1) // returns a "moment"

sugar.js

糖.js

var d = Date.past("monday") // returns a js Date object

I much prefer sugar and after some months with moment.js now switch to sugar.js. it is clearer and integrates nicely with Javascripts' Date class.

我更喜欢糖,在使用 moment.js 几个月后现在切换到 Sugar.js。它更清晰,并与 Javascripts 的 Date 类很好地集成。

OP cases are covered by both libs, for sugar.js see http://sugarjs.com/dates

两个库都涵盖了 OP 案例,对于 Sugar.js,请参见http://sugarjs.com/dates

回答by boreq

This js script is very nice. All you have to do is to execute it. All <time>tags will be changed to relative dates and updated every few minutes, so the relative time will always be up to date.

这个js脚本非常好。您所要做的就是执行它。所有<time>标签都将更改为相对日期并每隔几分钟更新一次,因此相对时间将始终是最新的。

http://timeago.yarp.com/

http://timeago.yarp.com/

回答by RoboKozo

Sounds like you could use http://www.datejs.com/

听起来你可以使用http://www.datejs.com/

They have an example on the main page that does exactly what you're describing!

他们在主页上有一个示例,它完全符合您的描述!

EDIT: Actually, I think I reversed your question in my head. In any case, I think you could check it out as it's a really great library anyway!

编辑:实际上,我想我在脑海中颠倒了你的问题。无论如何,我认为您可以检查一下,因为无论如何它都是一个非常棒的图书馆!

EDIT x2: I'm going to echo what the others have said http://momentjs.com/is probably the best choice available right now.

编辑 x2:我将回应其他人所说的http://momentjs.com/可能是目前可用的最佳选择。

EDIT x3: I haven't used date.js in over a year. I'm exclusively using momentjs for all my date related needs.

编辑 x3:我一年多没有使用过 date.js。我专门使用 momentjs 来满足我所有与日期相关的需求。