91

我正在寻找一个很好的 JS 片段来将时间戳(例如来自 Twitter API)转换为一个很好的用户友好的相对时间(例如 2 秒前、一周前等)。

有人愿意分享一些他们最喜欢的方法(最好不使用插件)吗?

4

14 回答 14

175

好吧,如果您不太关心准确性,那很容易。琐碎的方法有什么问题?

function timeDifference(current, previous) {

    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;

    var elapsed = current - previous;

    if (elapsed < msPerMinute) {
         return Math.round(elapsed/1000) + ' seconds ago';   
    }

    else if (elapsed < msPerHour) {
         return Math.round(elapsed/msPerMinute) + ' minutes ago';   
    }

    else if (elapsed < msPerDay ) {
         return Math.round(elapsed/msPerHour ) + ' hours ago';   
    }

    else if (elapsed < msPerMonth) {
        return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago';   
    }

    else if (elapsed < msPerYear) {
        return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago';   
    }

    else {
        return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago';   
    }
}

这里的工作示例。

如果这让您感到困扰,您可能需要调整它以更好地处理奇异值(例如1 day,而不是)。1 days

于 2011-05-24T10:33:06.987 回答
52

2021 年 4 月 4 日更新:

我已将以下代码转换为节点包。这是存储库


Intl.RelativeTimeFormat - 原生 API

[✔](12 月 18 日)第 3 阶段提案,已在Chrome 71
中实施 [✔](10 月 20 日)第 4 阶段(已完成),并准备纳入正式的 ECMAScript 标准

// in miliseconds
var units = {
  year  : 24 * 60 * 60 * 1000 * 365,
  month : 24 * 60 * 60 * 1000 * 365/12,
  day   : 24 * 60 * 60 * 1000,
  hour  : 60 * 60 * 1000,
  minute: 60 * 1000,
  second: 1000
}

var rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })

var getRelativeTime = (d1, d2 = new Date()) => {
  var elapsed = d1 - d2

  // "Math.abs" accounts for both "past" & "future" scenarios
  for (var u in units) 
    if (Math.abs(elapsed) > units[u] || u == 'second') 
      return rtf.format(Math.round(elapsed/units[u]), u)
}

// test-list of dates to compare with current date
[
  '10/20/1984',
  '10/20/2015',
  +new Date() - units.year,
  +new Date() - units.month,
  +new Date() - units.day,
  +new Date() - units.hour,
  +new Date() - units.minute,
  +new Date() + units.minute*2,
  +new Date() + units.day*7,
]
.forEach(d => console.log(   
  new Date(d).toLocaleDateString(),
  new Date(d).toLocaleTimeString(), 
  '(Relative to now) →',
  getRelativeTime(+new Date(d))
))

Intl.RelativeTimeFormat在V8 v7.1.179和 Chrome 71中默认可用。随着这个 API 变得更广泛可用,您会发现Moment.jsGlobalizedate- fns 等库放弃了对硬编码 CLDR 数据库的依赖,转而支持本机相对时间格式化功能,从而提高加载时间性能、解析- 以及编译时性能、运行时性能和内存使用情况。

于 2018-12-16T08:10:25.527 回答
29

这是 twitter 前没有插件的确切模仿:

function timeSince(timeStamp) {
  var now = new Date(),
    secondsPast = (now.getTime() - timeStamp) / 1000;
  if (secondsPast < 60) {
    return parseInt(secondsPast) + 's';
  }
  if (secondsPast < 3600) {
    return parseInt(secondsPast / 60) + 'm';
  }
  if (secondsPast <= 86400) {
    return parseInt(secondsPast / 3600) + 'h';
  }
  if (secondsPast > 86400) {
    day = timeStamp.getDate();
    month = timeStamp.toDateString().match(/ [a-zA-Z]*/)[0].replace(" ", "");
    year = timeStamp.getFullYear() == now.getFullYear() ? "" : " " + timeStamp.getFullYear();
    return day + " " + month + year;
  }
}

const currentTimeStamp = new Date().getTime();

console.log(timeSince(currentTimeStamp));

要点https://gist.github.com/timuric/11386129

小提琴http://jsfiddle.net/qE8Lu/1/

希望能帮助到你。

于 2014-04-28T22:49:22.700 回答
7

受 Diego Castillo awnser和timeago.js 插件的启发,我为此编写了自己的 vanilla 插件。

var timeElement = document.querySelector('time'),
    time = new Date(timeElement.getAttribute('datetime'));

timeElement.innerText = TimeAgo.inWords(time.getTime());

var TimeAgo = (function() {
  var self = {};
  
  // Public Methods
  self.locales = {
    prefix: '',
    sufix:  'ago',
    
    seconds: 'less than a minute',
    minute:  'about a minute',
    minutes: '%d minutes',
    hour:    'about an hour',
    hours:   'about %d hours',
    day:     'a day',
    days:    '%d days',
    month:   'about a month',
    months:  '%d months',
    year:    'about a year',
    years:   '%d years'
  };
  
  self.inWords = function(timeAgo) {
    var seconds = Math.floor((new Date() - parseInt(timeAgo)) / 1000),
        separator = this.locales.separator || ' ',
        words = this.locales.prefix + separator,
        interval = 0,
        intervals = {
          year:   seconds / 31536000,
          month:  seconds / 2592000,
          day:    seconds / 86400,
          hour:   seconds / 3600,
          minute: seconds / 60
        };
    
    var distance = this.locales.seconds;
    
    for (var key in intervals) {
      interval = Math.floor(intervals[key]);
      
      if (interval > 1) {
        distance = this.locales[key + 's'];
        break;
      } else if (interval === 1) {
        distance = this.locales[key];
        break;
      }
    }
    
    distance = distance.replace(/%d/i, interval);
    words += distance + separator + this.locales.sufix;

    return words.trim();
  };
  
  return self;
}());


// USAGE
var timeElement = document.querySelector('time'),
    time = new Date(timeElement.getAttribute('datetime'));

timeElement.innerText = TimeAgo.inWords(time.getTime());
<time datetime="2016-06-13"></time>

于 2016-06-14T04:01:32.407 回答
5
const units = [
  ['year', 31536000000],
  ['month', 2628000000],
  ['day', 86400000],
  ['hour', 3600000],
  ['minute', 60000],
  ['second', 1000],
]

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = elapsed => {
  for (const [unit, amount] of units) {
    if (Math.abs(elapsed) > amount || unit === 'second') {
      return rtf.format(Math.round(elapsed/amount), unit)
    }
  }
}

打高尔夫球玩得很开心,192b呵呵

const relatime = e=>{for(let[u,a]of Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})){if(Math.abs(e)>a||a===1e3){return new Intl.RelativeTimeFormat('en',{style:'narrow'}).format(~~(e/a),u)}}}

我还在打高尔夫球时测试了一个功能版本:

const rtf = new Intl.RelativeTimeFormat('en', { style:'narrow'})
const relatime = Object.entries({year:31536e6,month:2628e6,day:864e5,hour:36e5,minute:6e4,second:1e3})
  .reduce((f, [unit, amount]) => amount === 1e3
    ? f(elapsed => rtf.format(Math.round(elapsed/amount), unit))
    : next => f(e => Math.abs(e) < amount
      ? next(elapsed)
      : rtf.format(Math.round(elapsed/amount), unit)), _=>_)

好吧,我现在真的得回去工作了……

于 2020-02-18T16:57:10.220 回答
5

Typescript 和 Intl.RelativeTimeFormat (2020)

使用 Web API RelativeTimeFormat结合了 @vsync 和 @kigiri 方法的Typescript实现。

const units: {unit: Intl.RelativeTimeFormatUnit; ms: number}[] = [
    {unit: "year", ms: 31536000000},
    {unit: "month", ms: 2628000000},
    {unit: "day", ms: 86400000},
    {unit: "hour", ms: 3600000},
    {unit: "minute", ms: 60000},
    {unit: "second", ms: 1000},
];
const rtf = new Intl.RelativeTimeFormat("en", {numeric: "auto"});

/**
 * Get language-sensitive relative time message from Dates.
 * @param relative  - the relative dateTime, generally is in the past or future
 * @param pivot     - the dateTime of reference, generally is the current time
 */
export function relativeTimeFromDates(relative: Date | null, pivot: Date = new Date()): string {
    if (!relative) return "";
    const elapsed = relative.getTime() - pivot.getTime();
    return relativeTimeFromElapsed(elapsed);
}

/**
 * Get language-sensitive relative time message from elapsed time.
 * @param elapsed   - the elapsed time in milliseconds
 */
export function relativeTimeFromElapsed(elapsed: number): string {
    for (const {unit, ms} of units) {
        if (Math.abs(elapsed) >= ms || unit === "second") {
            return rtf.format(Math.round(elapsed / ms), unit);
        }
    }
    return "";
}
于 2021-02-26T17:06:42.063 回答
1

对于任何感兴趣的人,我最终创建了一个 Handlebars 助手来执行此操作。用法:

    {{#beautify_date}}
        {{timestamp_ms}}
    {{/beautify_date}}

帮手:

    Handlebars.registerHelper('beautify_date', function(options) {
        var timeAgo = new Date(parseInt(options.fn(this)));

        if (Object.prototype.toString.call(timeAgo) === "[object Date]") {
            if (isNaN(timeAgo.getTime())) {
                return 'Not Valid';
            } else {
                var seconds = Math.floor((new Date() - timeAgo) / 1000),
                intervals = [
                    Math.floor(seconds / 31536000),
                    Math.floor(seconds / 2592000),
                    Math.floor(seconds / 86400),
                    Math.floor(seconds / 3600),
                    Math.floor(seconds / 60)
                ],
                times = [
                    'year',
                    'month',
                    'day',
                    'hour',
                    'minute'
                ];

                var key;
                for(key in intervals) {
                    if (intervals[key] > 1)  
                        return intervals[key] + ' ' + times[key] + 's ago';
                    else if (intervals[key] === 1) 
                        return intervals[key] + ' ' + times[key] + ' ago';
                }

                return Math.floor(seconds) + ' seconds ago';
            }
        } else {
            return 'Not Valid';
        }
    });
于 2014-10-21T18:50:17.990 回答
1

如果您需要多语言并且不想添加像moment 这样的大库。来自 yahoo 的intl-relativeformat它是一个不错的解决方案。

var rf = new IntlRelativeFormat('en-US');

var posts = [
    {
        id   : 1,
        title: 'Some Blog Post',
        date : new Date(1426271670524)
    },
    {
        id   : 2,
        title: 'Another Blog Post',
        date : new Date(1426278870524)
    }
];

posts.forEach(function (post) {
    console.log(rf.format(post.date));
});
// => "3 hours ago"
// => "1 hour ago"
于 2018-01-31T14:41:18.547 回答
1

MomentJS 答案


对于 Moment.js 用户,它具有 fromNow() 函数,从当前日期/时间返回“x 天”或“x 小时前”。

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years
于 2019-07-01T08:33:35.983 回答
1

像 OP 一样,我倾向于避免使用我自己编写的代码的插件和包。当然,然后我最终会编写自己的包。

我创建了这个 NPM 包,因此我可以轻松地将任何日期转换为相对时间字符串(例如,“昨天”、“上周”、“2 年前”),并带有国际化 (i18n) 和本地化 (l10n) 的翻译。

随意查看源代码;这是一个很小的单个文件。存储库中的大部分内容用于单元测试、版本控制和发布到 NPM。

export default class RTF {
    formatters;
    options;

    /**
     * @param options {{localeMatcher: string?, numeric: string?, style: string?}} Intl.RelativeTimeFormat() options
     */
    constructor(options = RTF.defaultOptions) {
        this.options = options;
        this.formatters = { auto: new Intl.RelativeTimeFormat(undefined, this.options) };
    }

    /**
     * Add a formatter for a given locale.
     *
     * @param locale {string} A string with a BCP 47 language tag, or an array of such strings
     * @returns {boolean} True if locale is supported; otherwise false
     */
    addLocale(locale) {
        if (!Intl.RelativeTimeFormat.supportedLocalesOf(locale).includes(locale)) {
            return false;
        }
        if (!this.formatters.hasOwnProperty(locale)) {
            this.formatters[locale] = new Intl.RelativeTimeFormat(locale, this.options);
        }
        return true;
    }

    /**
     * Format a given date as a relative time string, with support for i18n.
     *
     * @param date {Date|number|string} Date object (or timestamp, or valid string representation of a date) to format
     * @param locale {string?} i18n code to use (e.g. 'en', 'fr', 'zh'); if omitted, default locale of runtime is used
     * @returns {string} Localized relative time string (e.g. '1 minute ago', '12 hours ago', '3 days ago')
     */
    format(date, locale = "auto") {
        if (!(date instanceof Date)) {
            date = new Date(Number.isNaN(date) ? Date.parse(date) : date);
        }
        if (!this.formatters.hasOwnProperty(locale) && !this.addLocale(locale)) {
            locale = "auto";
        }

        const elapsed = date - Date.now();

        for (let i = 0; i < RTF.units.length; i++) {
            const { unit, value } = RTF.units[i];
            if (unit === 'second' || Math.abs(elapsed) >= value) {
                return this.formatters[locale].format(Math.round(elapsed/value), unit);
            }
        }
    }

    /**
     * Generate HTTP middleware that works with popular frameworks and i18n tools like Express and i18next.
     *
     * @param rtf {RTF?} Instance of RTF to use; defaults to a new instance with default options
     * @param reqProp {string?} Property name to add to the HTTP request context; defaults to `rtf`
     * @param langProp {string?} Property of HTTP request context where language is stored; defaults to `language`
     * @returns {function(*, *, *): *} HTTP middleware function
     */
    static httpMiddleware(rtf = new RTF(), reqProp = "rtf", langProp = "language") {
        return (req, res, next) => {
            req[reqProp] = (date) => rtf.format(date, req[langProp]);
            next();
        };
    }

    /**
     * Default options object used by Intl.RelativeTimeFormat() constructor.
     *
     * @type {{localeMatcher: string, numeric: string, style: string}}
     */
    static defaultOptions = {
        localeMatcher: "best fit",
        numeric: "auto", // this intentionally differs from Intl.RelativeTimeFormat(), because "always" is dumb
        style: "long",
    };

    /**
     * Used to determine the arguments to pass to Intl.RelativeTimeFormat.prototype.format().
     */
    static units = [
        { unit: "year", value: 365 * 24 * 60 * 60 * 1000 },
        { unit: "month", value: 365 / 12 * 24 * 60 * 60 * 1000 },
        { unit: "week", value: 7 * 24 * 60 * 60 * 1000 },
        { unit: "day", value: 24 * 60 * 60 * 1000 },
        { unit: "hour", value: 60 * 60 * 1000 },
        { unit: "minute", value: 60 * 1000 },
        { unit: "second", value: 1000 },
    ];

    /**
     * Enumerated values for options object used by Intl.RelativeTimeFormat() constructor.
     *
     * @type {{localeMatcher: {lookup: string, default: string, bestFit: string}, numeric: {always: string, default: string, auto: string}, style: {default: string, short: string, narrow: string, long: string}}}
     */
    static opt = {
        localeMatcher: {
            bestFit: "best fit",
            lookup: "lookup",
        },
        numeric: {
            always: "always",
            auto: "auto",
        },
        style: {
            long: "long",
            narrow: "narrow",
            short: "short",
        },
    };
}

主要特点

为什么使用它而不是 Intl.RelativeTimeFormat.prototype.format()?

Intl.RelativeTimeFormat.prototype.format()接受两个参数:值和单位。

const rtf = new Intl.RelativeTimeFormat("en", { style: "narrow" });

expect(rtf.format(-1, "day")).toBe("1 day ago");
expect(rtf.format(10, "seconds")).toBe("in 10 sec.");

为了转换Date对象、时间戳或日期字符串,您需要编写一堆样板文件。这个库为您省去了这个麻烦,并且还可以用于为您的 REST API 生成一个中间件函数,该函数与您的 i18n 库一起使用。

于 2022-01-21T19:23:26.750 回答
0

存在日期时间插件是因为很难做到正确。这段解释日期时间不一致的视频将对这个问题有所了解。

以上所有没有插件的解决方案都是不正确的。

最好使用插件处理日期和时间。在处理它的数百个插件中,我们使用Moment.js,它正在完成这项工作。

twitter API 文档中我们可以看到他们的时间戳格式:

"created_at":"Wed Aug 27 13:08:45 +0000 2008"

我们可以用Moment.js来解析它

const postDatetime = moment(
  "Wed Aug 27 13:08:45 +0000 2008",
  "dddd, MMMM Do, h:mm:ss a, YYYY"
);
const now = moment();
const timeAgo = now.diff(postDatetime, 'seconds');

要为 指定首选时间单位diff,我们可以使用isSame方法。例如:

if (now.isSame(postDatetime, 'day')) {
  const timeUnit = 'days';
}

总体而言,构建类似:

`Posted ${timeAgo} ${timeUnit} ago`;

请参阅插件的文档以处理相对时间(即:“多久前?”)计算。

于 2016-12-04T12:27:00.447 回答
0

(2021) 如果您只需要天数,例如243 天前127 天后,那么它可以非常简单:

function relativeDays(timestamp) {
  const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  const aDay = 1000 * 60 * 60 * 24;
  const diffInDays = Math.round((timestamp - Date.now()) / aDay);
  return rtf.format(diffInDays, 'day');
}

尝试运行以下代码段:

function relativeDays(timestamp) {
  const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
  const aDay = 1000 * 60 * 60 * 24;
  const diffInDays = Math.round((timestamp - Date.now()) / aDay);
  return rtf.format(diffInDays, 'day');
}

console.log(relativeDays(Date.now() - 86400000)); // "yesterday"
console.log(relativeDays(Date.now())); // "today"
console.log(relativeDays(Date.now() + 86400000)); // "tomorrow"
console.log(relativeDays(Date.now() - 8640000000)); // "100 days ago"
console.log(relativeDays(Date.now() + 8640000000)); // "in 100 days"

// Note my timestamp argument is a number in ms, if you want to pass in a Date object, modify the function accordingly

于 2021-11-06T09:03:57.737 回答
0

根据 twitter 的当前设计添加我的时间标签代码

function timeElapsed(targetTimestamp:string) {
    let currentDate=new Date();
    let currentTimeInms = currentDate.getTime();
    let targetDate=new Date(targetTimestamp);
    let targetTimeInms = targetDate.getTime();
    let elapsed = Math.floor((currentTimeInms-targetTimeInms)/1000);
    if(elapsed<1) {
        return '0s';
    }
    if(elapsed<60) { //< 60 sec
        return `${elapsed}s`;
    }
    if (elapsed < 3600) { //< 60 minutes
        return `${Math.floor(elapsed/(60))}m`;
    }
    if (elapsed < 86400) { //< 24 hours
        return `${Math.floor(elapsed/(3600))}h`;
    }
    if (elapsed < 604800) { //<7 days
        return `${Math.floor(elapsed/(86400))}d`;
    }
    if (elapsed < 2628000) { //<1 month
        return `${targetDate.getDate()} ${MonthNames[targetDate.getMonth()]}`;
    }   
    return `${targetDate.getDate()} ${MonthNames[targetDate.getMonth()]} ${targetDate.getFullYear()}`; //more than a monh
}
于 2021-12-31T17:59:28.947 回答
-1

为此,您可以使用 machinepack-datetime。其定义的 API 简单明了。

tutorialSchema.virtual('createdOn').get(function () {
    const DateTime = require('machinepack-datetime');
    let timeAgoString = "";
    try {
        timeAgoString = DateTime.timeFrom({
            toWhen: DateTime.parse({
                datetime: this.createdAt
            }).execSync(),
            fromWhen: new Date().getTime()
        }).execSync();
    } catch(err) {
        console.log('error getting createdon', err);
    }
    return timeAgoString; // a second ago
});
于 2017-12-08T17:26:28.637 回答