给定特定的DateTime值,如何显示相对时间,例如:
2小时前3天前一个月前
给定特定的DateTime值,如何显示相对时间,例如:
2小时前3天前一个月前
当前回答
// Calculate total days in current year
int daysInYear;
for (var i = 1; i <= 12; i++)
daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);
// Past date
DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));
// Calculate difference between current date and past date
double diff = (DateTime.Now - dateToCompare).TotalMilliseconds;
TimeSpan ts = TimeSpan.FromMilliseconds(diff);
var years = ts.TotalDays / daysInYear; // Years
var months = ts.TotalDays / (daysInYear / (double)12); // Months
var weeks = ts.TotalDays / 7; // Weeks
var days = ts.TotalDays; // Days
var hours = ts.TotalHours; // Hours
var minutes = ts.TotalMinutes; // Minutes
var seconds = ts.TotalSeconds; // Seconds
if (years >= 1)
Console.WriteLine(Math.Round(years, 0) + " year(s) ago");
else if (months >= 1)
Console.WriteLine(Math.Round(months, 0) + " month(s) ago");
else if (weeks >= 1)
Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago");
else if (days >= 1)
Console.WriteLine(Math.Round(days, 0) + " days(s) ago");
else if (hours >= 1)
Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago");
else if (minutes >= 1)
Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago");
else if (seconds >= 1)
Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago");
Console.ReadLine();
其他回答
在Java中有没有一种简单的方法可以做到这一点?java.util.Date类似乎相当有限。
下面是我的快速而肮脏的Java解决方案:
import java.util.Date;
import javax.management.timer.Timer;
String getRelativeDate(Date date) {
long delta = new Date().getTime() - date.getTime();
if (delta < 1L * Timer.ONE_MINUTE) {
return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago";
}
if (delta < 2L * Timer.ONE_MINUTE) {
return "a minute ago";
}
if (delta < 45L * Timer.ONE_MINUTE) {
return toMinutes(delta) + " minutes ago";
}
if (delta < 90L * Timer.ONE_MINUTE) {
return "an hour ago";
}
if (delta < 24L * Timer.ONE_HOUR) {
return toHours(delta) + " hours ago";
}
if (delta < 48L * Timer.ONE_HOUR) {
return "yesterday";
}
if (delta < 30L * Timer.ONE_DAY) {
return toDays(delta) + " days ago";
}
if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month
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 long toSeconds(long date) {
return date / 1000L;
}
private long toMinutes(long date) {
return toSeconds(date) / 60L;
}
private long toHours(long date) {
return toMinutes(date) / 60L;
}
private long toDays(long date) {
return toHours(date) / 24L;
}
private long toMonths(long date) {
return toDays(date) / 30L;
}
private long toYears(long date) {
return toMonths(date) / 365L;
}
Nuget上还有一个名为Humanizr的软件包,它实际上运行得很好,并且在.NET Foundation中。
DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"
DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"
TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"
Scott Hanselman在他的博客上写了一篇文章
文斯回答的土耳其语本地化版本。
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 + " saniye önce";
if (delta < 45 * MINUTE)
return ts.Minutes + " dakika önce";
if (delta < 24 * HOUR)
return ts.Hours + " saat önce";
if (delta < 48 * HOUR)
return "dün";
if (delta < 30 * DAY)
return ts.Days + " gün önce";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months + " ay önce";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years + " yıl önce";
}
下面是我作为DateTime类的扩展方法添加的一个实现,它处理未来和过去的日期,并提供了一个近似选项,允许您指定要查找的详细程度(“3小时前”与“3小时、23分钟、12秒前”):
using System.Text;
/// <summary>
/// Compares a supplied date to the current date and generates a friendly English
/// comparison ("5 days ago", "5 days from now")
/// </summary>
/// <param name="date">The date to convert</param>
/// <param name="approximate">When off, calculate timespan down to the second.
/// When on, approximate to the largest round unit of time.</param>
/// <returns></returns>
public static string ToRelativeDateString(this DateTime value, bool approximate)
{
StringBuilder sb = new StringBuilder();
string suffix = (value > DateTime.Now) ? " from now" : " ago";
TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));
if (timeSpan.Days > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Days,
(timeSpan.Days > 1) ? "days" : "day");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Hours > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Minutes > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Seconds > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second");
if (approximate) return sb.ToString() + suffix;
}
if (sb.Length == 0) return "right now";
sb.Append(suffix);
return sb.ToString();
}
iPhone Objective-C版本
+ (NSString *)timeAgoString:(NSDate *)date {
int delta = -(int)[date timeIntervalSinceNow];
if (delta < 60)
{
return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta];
}
if (delta < 120)
{
return @"a minute ago";
}
if (delta < 2700)
{
return [NSString stringWithFormat:@"%i minutes ago", delta/60];
}
if (delta < 5400)
{
return @"an hour ago";
}
if (delta < 24 * 3600)
{
return [NSString stringWithFormat:@"%i hours ago", delta/3600];
}
if (delta < 48 * 3600)
{
return @"yesterday";
}
if (delta < 30 * 24 * 3600)
{
return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)];
}
if (delta < 12 * 30 * 24 * 3600)
{
int months = delta/(30*24*3600);
return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months];
}
else
{
int years = delta/(12*30*24*3600);
return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years];
}
}