问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
问题是如何将JavaScript Date格式化为一个字符串,声明时间经过,类似于您在Stack Overflow上看到的时间显示方式。
e.g.
1分钟前 1小时前 1天前 1个月前 一年前
当前回答
Lokely使用的一个简短版本:
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 1 }
];
function timeSince(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
const interval = intervals.find(i => i.seconds < seconds);
const count = Math.floor(seconds / interval.seconds);
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
}
其他回答
我还没有检查(虽然这并不难),但我认为Stack Exchange站点使用jquery。Timeago插件来创建这些时间字符串。
这个插件使用起来很简单,而且很干净,还能自动更新。
下面是一个简单的例子(来自插件的主页):
First, load jQuery and the plugin: <script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.timeago.js" type="text/javascript"></script> Now, let's attach it to your timestamps on DOM ready: jQuery(document).ready(function() { jQuery("abbr.timeago").timeago(); }); This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">about a year ago</abbr> which yields: about a year ago. As time passes, the timestamps will automatically update.
function calDateAgo(dString=null){
//var dString = "2021-04-1 12:00:00";
var d1 = new Date(dString);
var d2 = new Date();
var t2 = d2.getTime();
var t1 = d1.getTime();
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
var time_obj = {};
time_obj.year = d2.getFullYear()-d1.getFullYear();
time_obj.month = (d2M+12*d2Y)-(d1M+12*d1Y);
time_obj.week = parseInt((t2-t1)/(24*3600*1000*7));
time_obj.day = parseInt((t2-t1)/(24*3600*1000));
time_obj.hour = parseInt((t2-t1)/(3600*1000));
time_obj.minute = parseInt((t2-t1)/(60*1000));
time_obj.second = parseInt((t2-t1)/(1000));
for (const obj_key in time_obj) {
if(time_obj[obj_key] == 0){
delete time_obj[obj_key];
}
}
var ago_text = 'just now';
if(typeof Object.keys(time_obj)[0] != 'undefined'){
var time_key = Object.keys(time_obj)[0];
var time_val = time_obj[Object.keys(time_obj)[0]];
time_key += (time_val > 1) ? 's':'';
ago_text = time_val+' '+time_key+' ago';
}
return ago_text;
}
我的解决方案。
(function(global){
const SECOND = 1;
const MINUTE = 60;
const HOUR = 3600;
const DAY = 86400;
const MONTH = 2629746;
const YEAR = 31556952;
const DECADE = 315569520;
global.timeAgo = function(date){
var now = new Date();
var diff = Math.round(( now - date ) / 1000);
var unit = '';
var num = 0;
var plural = false;
switch(true){
case diff <= 0:
return 'just now';
break;
case diff < MINUTE:
num = Math.round(diff / SECOND);
unit = 'sec';
plural = num > 1;
break;
case diff < HOUR:
num = Math.round(diff / MINUTE);
unit = 'min';
plural = num > 1;
break;
case diff < DAY:
num = Math.round(diff / HOUR);
unit = 'hour';
plural = num > 1;
break;
case diff < MONTH:
num = Math.round(diff / DAY);
unit = 'day';
plural = num > 1;
break;
case diff < YEAR:
num = Math.round(diff / MONTH);
unit = 'month';
plural = num > 1;
break;
case diff < DECADE:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
break;
default:
num = Math.round(diff / YEAR);
unit = 'year';
plural = num > 1;
}
var str = '';
if(num){
str += `${num} `;
}
str += `${unit}`;
if(plural){
str += 's';
}
str += ' ago';
return str;
}
})(window);
console.log(timeAgo(new Date()));
console.log(timeAgo(new Date('Jun 03 2018 15:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Jun 03 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2018 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2017 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('May 28 2000 13:12:19 GMT+0300 (FLE Daylight Time)')));
console.log(timeAgo(new Date('Sep 10 1994 13:12:19 GMT+0300 (FLE Daylight Time)')));
Lokely使用的一个简短版本:
const intervals = [
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 1 }
];
function timeSince(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
const interval = intervals.find(i => i.seconds < seconds);
const count = Math.floor(seconds / interval.seconds);
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`;
}
简单易读版本:
const relativeTimePeriods = [
[31536000, 'year'],
[2419200, 'month'],
[604800, 'week'],
[86400, 'day'],
[3600, 'hour'],
[60, 'minute'],
[1, 'second']
];
function relativeTime(date, isUtc=true) {
if (!(date instanceof Date)) date = new Date(date * 1000);
const seconds = (new Date() - date) / 1000;
for (let [secondsPer, name] of relativeTimePeriods) {
if (seconds >= secondsPer) {
const amount = Math.floor(seconds / secondsPer);
return `${amount} ${name}${amount ? 's' : ''}s ago`;
}
}
return 'Just now';
}