我想以人性化的格式显示一些相对于当前日期的日期.
I'd like to display some dates as relative to the current date in a human-friendly format.
人类友好的相对日期示例:
Examples of human-friendly relative dates:
基本上忠实地保留最高数量级(并且优先考虑,仅在超过其中 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:
有任何流行的图书馆吗?
Any popular libraries for this?
自从我写了这个答案,一个众所周知的可用库是 moment.js.
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.
假设 date 是一个实例化的 Date 对象,用于您要与之进行比较的时间.
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 库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
Browserify,Babel 6,Gulp - 传播运算符上的意外令牌Browserify, Babel 6, Gulp - Unexpected token on spread operator(Browserify,Babel 6,Gulp - 传播运算符上的意外令牌)
是否可以将标志传递给 Gulp 以使其以不同的方式Is it possible to pass a flag to Gulp to have it run tasks in different ways?(是否可以将标志传递给 Gulp 以使其以不同的方式运行任务
为什么我们需要在全局和本地安装 gulp?Why do we need to install gulp globally and locally?(为什么我们需要在全局和本地安装 gulp?)
如何一个接一个地依次运行 Gulp 任务How to run Gulp tasks sequentially one after the other(如何一个接一个地依次运行 Gulp 任务)
打开 Javascript 文件时 Visual Studio 2015 崩溃Visual Studio 2015 crashes when opening Javascript files(打开 Javascript 文件时 Visual Studio 2015 崩溃)
检测 FLASH 插件崩溃Detect FLASH plugin crashes(检测 FLASH 插件崩溃)