给定特定的DateTime值,如何显示相对时间,例如:
2小时前3天前一个月前
给定特定的DateTime值,如何显示相对时间,例如:
2小时前3天前一个月前
当前回答
用于客户端gwt的Java:
import java.util.Date;
public class RelativeDateFormat {
private static final long ONE_MINUTE = 60000L;
private static final long ONE_HOUR = 3600000L;
private static final long ONE_DAY = 86400000L;
private static final long ONE_WEEK = 604800000L;
public static String format(Date date) {
long delta = new Date().getTime() - date.getTime();
if (delta < 1L * ONE_MINUTE) {
return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta)
+ " seconds ago";
}
if (delta < 2L * ONE_MINUTE) {
return "one minute ago";
}
if (delta < 45L * ONE_MINUTE) {
return toMinutes(delta) + " minutes ago";
}
if (delta < 90L * ONE_MINUTE) {
return "one hour ago";
}
if (delta < 24L * ONE_HOUR) {
return toHours(delta) + " hours ago";
}
if (delta < 48L * ONE_HOUR) {
return "yesterday";
}
if (delta < 30L * ONE_DAY) {
return toDays(delta) + " days ago";
}
if (delta < 12L * 4L * ONE_WEEK) {
long months = toMonths(delta);
return months <= 1 ? "one month ago" : months + " months ago";
} else {
long years = toYears(delta);
return years <= 1 ? "one year ago" : years + " years ago";
}
}
private static long toSeconds(long date) {
return date / 1000L;
}
private static long toMinutes(long date) {
return toSeconds(date) / 60L;
}
private static long toHours(long date) {
return toMinutes(date) / 60L;
}
private static long toDays(long date) {
return toHours(date) / 24L;
}
private static long toMonths(long date) {
return toDays(date) / 30L;
}
private static long toYears(long date) {
return toMonths(date) / 365L;
}
}
其他回答
我从比尔·盖茨的一个博客中得到了这个答案。我需要在我的浏览器历史记录中找到它,我会给你链接。
执行相同操作的Javascript代码(按要求):
function posted(t) {
var now = new Date();
var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
if (diff < 60) { return 'less than a minute ago'; }
else if (diff < 120) { return 'about a minute ago'; }
else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
else if (diff < (5400)) { return 'about an hour ago'; }
else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
else if (diff < (172800)) { return '1 day ago'; }
else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}
基本上,你是以秒为单位工作的。
Jeff,您的代码很好,但使用常量可以更清晰(如代码完成中所建议的)。
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "a minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "an hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "yesterday";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
简单且100%的工作解决方案。
处理过去和将来的时间。。以防万一
public string GetTimeSince(DateTime postDate)
{
string message = "";
DateTime currentDate = DateTime.Now;
TimeSpan timegap = currentDate - postDate;
if (timegap.Days > 365)
{
message = string.Format(L("Ago") + " {0} " + L("Years"), (((timegap.Days) / 30) / 12));
}
else if (timegap.Days > 30)
{
message = string.Format(L("Ago") + " {0} " + L("Months"), timegap.Days/30);
}
else if (timegap.Days > 0)
{
message = string.Format(L("Ago") + " {0} " + L("Days"), timegap.Days);
}
else if (timegap.Hours > 0)
{
message = string.Format(L("Ago") + " {0} " + L("Hours"), timegap.Hours);
}
else if (timegap.Minutes > 0)
{
message = string.Format(L("Ago") + " {0} " + L("Minutes"), timegap.Minutes);
}
else if (timegap.Seconds > 0)
{
message = string.Format(L("Ago") + " {0} " + L("Seconds"), timegap.Seconds);
}
// let's handle future times..just in case
else if (timegap.Days < -365)
{
message = string.Format(L("In") + " {0} " + L("Years"), (((Math.Abs(timegap.Days)) / 30) / 12));
}
else if (timegap.Days < -30)
{
message = string.Format(L("In") + " {0} " + L("Months"), ((Math.Abs(timegap.Days)) / 30));
}
else if (timegap.Days < 0)
{
message = string.Format(L("In") + " {0} " + L("Days"), Math.Abs(timegap.Days));
}
else if (timegap.Hours < 0)
{
message = string.Format(L("In") + " {0} " + L("Hours"), Math.Abs(timegap.Hours));
}
else if (timegap.Minutes < 0)
{
message = string.Format(L("In") + " {0} " + L("Minutes"), Math.Abs(timegap.Minutes));
}
else if (timegap.Seconds < 0)
{
message = string.Format(L("In") + " {0} " + L("Seconds"), Math.Abs(timegap.Seconds));
}
else
{
message = "a bit";
}
return message;
}
这是我的功能,就像一个魅力:)
public static string RelativeDate(DateTime theDate)
{
var span = DateTime.Now - theDate;
if (span.Days > 365)
{
var years = (span.Days / 365);
if (span.Days % 365 != 0)
years += 1;
return $"about {years} {(years == 1 ? "year" : "years")} ago";
}
if (span.Days > 30)
{
var months = (span.Days / 30);
if (span.Days % 31 != 0)
months += 1;
return $"about {months} {(months == 1 ? "month" : "months")} ago";
}
if (span.Days > 0)
return $"about {span.Days} {(span.Days == 1 ? "day" : "days")} ago";
if (span.Hours > 0)
return $"about {span.Hours} {(span.Hours == 1 ? "hour" : "hours")} ago";
if (span.Minutes > 0)
return $"about {span.Minutes} {(span.Minutes == 1 ? "minute" : "minutes")} ago";
if (span.Seconds > 5)
return $"about {span.Seconds} seconds ago";
return span.Seconds <= 5 ? "about 5 seconds ago" : string.Empty;
}
我也建议在客户端进行计算。服务器工作更少。
以下是我使用的版本(来自Zach Leatherman)
/*
* Javascript Humane Dates
* Copyright (c) 2008 Dean Landolt (deanlandolt.com)
* Re-write by Zach Leatherman (zachleat.com)
*
* Adopted from the John Resig's pretty.js
* at http://ejohn.org/blog/javascript-pretty-date
* and henrah's proposed modification
* at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
*
* Licensed under the MIT license.
*/
function humane_date(date_str){
var time_formats = [
[60, 'just now'],
[90, '1 minute'], // 60*1.5
[3600, 'minutes', 60], // 60*60, 60
[5400, '1 hour'], // 60*60*1.5
[86400, 'hours', 3600], // 60*60*24, 60*60
[129600, '1 day'], // 60*60*24*1.5
[604800, 'days', 86400], // 60*60*24*7, 60*60*24
[907200, '1 week'], // 60*60*24*7*1.5
[2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
[3942000, '1 month'], // 60*60*24*(365/12)*1.5
[31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
[47304000, '1 year'], // 60*60*24*365*1.5
[3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
[4730400000, '1 century'] // 60*60*24*365*100*1.5
];
var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
dt = new Date,
seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
token = ' ago',
i = 0,
format;
if (seconds < 0) {
seconds = Math.abs(seconds);
token = '';
}
while (format = time_formats[i++]) {
if (seconds < format[0]) {
if (format.length == 2) {
return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
} else {
return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
}
}
}
// overflow for centuries
if(seconds > 4730400000)
return Math.round(seconds / 4730400000) + ' centuries' + token;
return date_str;
};
if(typeof jQuery != 'undefined') {
jQuery.fn.humane_dates = function(){
return this.each(function(){
var date = humane_date(this.title);
if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
jQuery(this).text(date);
});
};
}