我有这个日期&小时格式2016-03-07 15:13:49
。我希望在1分钟前,1小时前或1年前显示它,具体取决于从现在开始的日期有多长。
答案 0 :(得分:2)
答案 1 :(得分:1)
您需要将日期格式转换为js date
对象,然后才能使用this回答中的timeSince
功能
var date = new Date('2016-03-07T15:13:49')
document.write("js date: " + date + "<br><br>");
document.write("timesince: ");
document.write(timeSince(date));
function timeSince(date) {
var seconds = Math.floor((new Date() - date) / 1000);
var interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds";
}
答案 2 :(得分:0)
var past_date = new Date('2016-07-28T05:13:49'); // the date will come here
var time_diff = new Date()- past_date; // getting the difference between the past date and the current date
var min = Math.floor(time_diff/60000); // Converting time in to minutes
var seconds = 59,
minutes = Math.floor(min%60),
hours = Math.floor(min/60);
if(hours > 24){ // Checking if the hours ids more than 24 to display as a day
var days = hours/24;
days = days.toFixed(0);
document.write("last updated:" + days + " days ago");
}else if(hours > 1){ // if time is less than the 24 hours it will display in hours
document.write("last updated:" + hours + " hours ago");
}else{
document.write("last updated:" + minutes + " minutes ago");
}