-
03-07-2019 - |
题
我在寻找一个模糊的日期算法。我刚开始写作之一,并意识到什么是一项繁重的任务。它很快变成一个很可怕的代码,以应付特殊情况下等之间的差异"昨天","上周"和"迟交的最后一个月的"所有这些都可以(在某些情况下)提到的同一天,但是单独正确的根据今天的日期。
我觉得肯定,必须有一个开放源模糊的日期格式,但我找不到它。理想的是我想的东西使用NSDate(OS x/iPhone)及其格式,但这并不是难点。任何人都不会知道的一个模糊的日期格式采取任何时期相对于现在和返回的一串等(但不限于):
- 几分钟前
- 在最后五分钟
- 今天早些时候
- 今天早上
- 昨晚
- 最后一个星期
- 上周三
- 上个月初
- 去年六月
- 几年前
在一个理想的世界,我想要串尽可能丰富的尽可能(即返回的随机变体在"刚刚"诸如"只是现在").
澄清。我在找一些更微妙于基本buckts和弦。我想要的东西,知道"昨天"和"最后一个星期三"既可以指以相同期间,但只有一个是正确的,当今天是星期四。
解决方案
这个问题应该让你开始。 它的代码这很网站使用计算出其相对的时间。它可能没有特定范围你想要的,但它们都足够容易添加一旦你得到了它安装。
其他提示
有一个酒店中NSDateFormatter-"doesRelativeDateFormatting".它只出现在10.6/ios系统4.0和后但它将日期的格式成一个相对的日期以正确的区域设置。
从 苹果的文件:
如果一个日期格式采用相对日期 格式化,在可能的替换 日组成部分,其输出 一短语,如"今日"或 "明天"—是指一个相对的 日期。可用的短语取决于 该区域的日期格式;然而,对于日期,在未来, 英语可能只允许"明天" 法国可以允许"一天之后 后天"中所说明的 下面的例子。
代码
以下是代码,这将打印出来的一个良好的数量相对串对于给定的区域设置。
NSLocale *locale = [NSLocale currentLocale];
// NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"] autorelease];
NSDateFormatter *relativeDateFormatter = [[NSDateFormatter alloc] init];
[relativeDateFormatter setTimeStyle:NSDateFormatterNoStyle];
[relativeDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[relativeDateFormatter setDoesRelativeDateFormatting:YES];
[relativeDateFormatter setLocale:locale];
NSDateFormatter *normalDateFormatter = [[NSDateFormatter alloc] init];
[normalDateFormatter setTimeStyle:NSDateFormatterNoStyle];
[normalDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[normalDateFormatter setDoesRelativeDateFormatting:NO];
[normalDateFormatter setLocale:locale];
NSString * lastUniqueString = nil;
for ( NSTimeInterval timeInterval = -60*60*24*400; timeInterval < 60*60*24*400; timeInterval += 60.0*60.0*24.0 )
{
NSDate * date = [NSDate dateWithTimeIntervalSinceNow:timeInterval];
NSString * relativeFormattedString = [relativeDateFormatter stringForObjectValue:date];
NSString * formattedString = [normalDateFormatter stringForObjectValue:date];
if ( [relativeFormattedString isEqualToString:lastUniqueString] || [relativeFormattedString isEqualToString:formattedString] )
continue;
NSLog( @"%@", relativeFormattedString );
lastUniqueString = relativeFormattedString;
}
注:
- 一个区域是不需要
- 还有 不许替换 英文。在撰写本文时没有 有:"昨天、今天、明天"。苹果公司可以包括更多的未来。
- 它是有趣的改变区域和看到 什么是提供其他语言 (法语有些多于英文, 例如)
- 如果,你可能会想订阅 UIApplicationSignificantTimeChangenotification
接口生成器
你可以设定"doesRelativeDateFormatting"酒店的接口建设者:
- 选择你的NSDateFormatter和 选择"的身份检查员"标签 检查专员的调色板(最后一个 一个[命令-6]).
- 根据该分部名为"用户 定义的运行时的属性"的,你可以 添加自己价值的一个关键在于选择对象(在这种情况下,你的NSDateFormatter的实例)。添加 "doesRelativeDateFormatting",选择 一个"Boolean"类型,和确保它的 检查。
- 还记得:它可能看起来像它并没有在所有的工作,但这可能是因为只有少数取代的价值为你的区域。试试至少一个日期为昨天、今天和明天之前你决定如果不是设立正确的。
你可能想看看轨的 distance_of_time_in_words
功能 date_helper.rb, 我已经粘贴如下。
# File vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb, line 59
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
I18n.with_options :locale => options[:locale], :scope => 'datetime.distance_in_words''datetime.distance_in_words' do |locale|
case distance_in_minutes
when 0..1
return distance_in_minutes == 0 ?
locale.t(:less_than_x_minutes, :count => 1) :
locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds
case distance_in_seconds
when 0..4 then locale.t :less_than_x_seconds, :count => 5
when 5..9 then locale.t :less_than_x_seconds, :count => 10
when 10..19 then locale.t :less_than_x_seconds, :count => 20
when 20..39 then locale.t :half_a_minute
when 40..59 then locale.t :less_than_x_minutes, :count => 1
else locale.t :x_minutes, :count => 1
end
when 2..44 then locale.t :x_minutes, :count => distance_in_minutes
when 45..89 then locale.t :about_x_hours, :count => 1
when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
when 1440..2879 then locale.t :x_days, :count => 1
when 2880..43199 then locale.t :x_days, :count => (distance_in_minutes / 1440).round
when 43200..86399 then locale.t :about_x_months, :count => 1
when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes / 43200).round
when 525600..1051199 then locale.t :about_x_years, :count => 1
else locale.t :over_x_years, :count => (distance_in_minutes / 525600).round
end
end
end
因此,这里是类别I写上NSDate对于那些仍然感兴趣。问题是那些变得有点不切实际的.它基本上是一个巨大的开声明(虽然我实施它的一系列联if()s来,使其更具可读性。
每个时段我然后从中选择一个随机设置的方式告诉的时间。
所有的一切,这非常高兴我们的一些用户,但我不确定这是值得努力。
NSTimeInterval const kTenSeconds = (10.0f );
NSTimeInterval const kOneMinute = (60.0f);
NSTimeInterval const kFiveMinutes = (5.0f*60.0f);
NSTimeInterval const kFifteenMinutes = (15.0f*60.0f) ;
NSTimeInterval const kHalfAnHour = (30.0f*60.0f) ;
NSTimeInterval const kOneHour = 3600.0f; // (60.0f * 60.0f);
NSTimeInterval const kHalfADay = (3600.0f * 12.0f);
NSTimeInterval const kOneDay = (3600.0f * 24.0f);
NSTimeInterval const kOneWeek = (3600.0f * 24.0f * 7.0f);
@implementation NSDate (Fuzzy)
-(NSString*)fuzzyStringRelativeToNow;
{
static NSArray* secondsStrings;
static NSArray* minuteStrings;
static NSArray* fiveMinuteStrings;
static NSArray* halfHourStrings;
static NSArray* earlyMonthStrings;
NSTimeInterval timeFromNow = [self timeIntervalSinceNow];
if((timeFromNow < 0)) // In the past
{
timeFromNow = - timeFromNow;
if ( (timeFromNow < kTenSeconds))
{
if(!secondsStrings)
{
secondsStrings = [[NSArray arrayWithObjects:@"just now",
//@"a few seconds ago",
//@"right this instant",
@"moments ago",
nil] retain];
}
unsigned int index = random() % ([secondsStrings count] - 1);
return [secondsStrings objectAtIndex:index];
}
if ( (timeFromNow < kOneMinute))
{
if(!minuteStrings)
{
minuteStrings = [[NSArray arrayWithObjects:@"just now",
@"very recently",
@"in the last minute",
nil] retain];
}
unsigned int index = random() % ([minuteStrings count] - 1);
return [minuteStrings objectAtIndex:index];
}
if (timeFromNow < kFiveMinutes)
{
if(!fiveMinuteStrings)
{
fiveMinuteStrings = [[NSArray arrayWithObjects:@"just now",
@"very recently",
//@"in the last minute",
@"a few minutes ago",
//@"in the last five minutes",
nil] retain];
}
unsigned int index = random() % ([fiveMinuteStrings count] - 1);
return [fiveMinuteStrings objectAtIndex:index];
}
if (timeFromNow < kFifteenMinutes)
{
return @"in the last 15 minutes";
}
if (timeFromNow < kHalfAnHour)
{
if(!halfHourStrings)
{
halfHourStrings = [[NSArray arrayWithObjects:@"in the last half hour",
//@"in the last half an hour",
@"in the last 30 minutes",
//@"about half an hour ago",
@"fairly recently",
nil] retain];
}
unsigned int index = random() % ([halfHourStrings count] - 1);
return [halfHourStrings objectAtIndex:index];
}
if (timeFromNow < kOneHour)
{
return @"in the last hour";
}
if ((timeFromNow < (kOneHour + kFiveMinutes)) && (timeFromNow > (kOneHour - kFiveMinutes)))
{
return @"about an hour ago";
}
if((timeFromNow < ((kOneHour*2.0f) + kFiveMinutes ))&& (timeFromNow > ((kOneHour*2.0f) - kFiveMinutes)))
{
return @"a couple of hours ago";
}
// Now we're over an hour, we need to calculate a few specific dates to compare against
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* todayComponents = [gregorian components:unitFlags fromDate:today];
todayComponents.hour = 12;
NSDate* noonToday = [gregorian dateFromComponents:todayComponents];
NSTimeInterval timeSinceNoonToday = [self timeIntervalSinceDate:noonToday];
if (timeSinceNoonToday > 0) // sometime since noon
{
if (timeSinceNoonToday > kOneHour * 9) // i.e. after 9pm today
return @"earlier tonight";
if (timeSinceNoonToday > kOneHour * 7) // i.e. after 7pm today
return @"earlier this evening";
if (timeSinceNoonToday < kOneHour * 1) // between noon and 1pm
return @"early this afternoon";
return @"this afternoon";
}
NSTimeInterval timeSinceMidnight = kHalfADay -timeSinceNoonToday; // Note sign is reversed.
if ((timeSinceNoonToday < 0) & (timeSinceNoonToday > -kHalfADay)) // between midnight and noon today
{
if (timeSinceMidnight < kFiveMinutes)
return @"around midnight";
if (timeSinceMidnight < kOneHour * 2) // up to 2am
return @"very early this morning";
if (timeSinceMidnight < kOneHour * 5) // up to 5am
return @"early this morning";
else if (timeSinceMidnight < kOneHour * 11)
return @"late this morning";
else
return @"this morning";
}
// NSTimeInterval timeSinceNoonYesterday = timeSinceNoonToday - kOneDay;
// timeSinceMidnight = -timeSinceMidnight;
if (timeSinceMidnight < kOneHour * 24) // not the day before...
{
if (timeSinceMidnight < kFiveMinutes)
return @"around midnight";
if (timeSinceMidnight < kFifteenMinutes)
return @"just before midnight";
if (timeSinceMidnight < kOneHour * 2) // after 10pm
return @"late last night";
if (timeSinceMidnight < kOneHour * 5) // After 7
return @"yesterday evening";
else if (timeSinceMidnight < kOneHour * 7)
return @"yesterday evening"; // after 5pm
else if (timeSinceMidnight < kOneHour * 7)
return @"yesterday evening"; // after 5pm
else if (timeSinceMidnight < kOneHour * 10)
return @"yesterday afternoon"; // after 5pm
else if (timeSinceMidnight < kOneHour * 12)
return @"early yesterday afternoon"; // before 1pm
else if (timeSinceMidnight < kOneHour * 13)
return @"late yesterday morning"; // after 11m
else if (timeSinceMidnight < kOneHour * 17)
return @"yesterday morning";
else
return @"early yesterday morning";
}
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
int integerSeconds = timeSinceMidnight;
int integerDay = kOneDay;
int secondsIntoDay = integerSeconds % integerDay;
NSString* formatString = @"last %@";
if (timeFromNow < kOneWeek)
{
if (secondsIntoDay < kFifteenMinutes)
formatString = @"around midnight on %@";
//else if (secondsIntoDay < kFifteenMinutes)
// formatString = @"just before midnight on %@";
else if (secondsIntoDay < kOneHour * 2) // after 10pm
formatString = @"late on %@ night";
else if (secondsIntoDay < kOneHour * 5) // After 7
formatString = @"on %@ evening";
else if (secondsIntoDay < kOneHour * 10)
formatString = @"on %@ afternoon"; // after 5pm
else if (secondsIntoDay < kOneHour * 12)
formatString = @"early on %@ afternoon"; // before 1pm
else if (secondsIntoDay < kOneHour * 13)
formatString = @"late on %@ morning"; // after 11am
else if (secondsIntoDay < kOneHour * 17)
formatString = @"on %@ morning";
else if (secondsIntoDay < kOneHour * 24) // not the day before...
formatString = @"early on %@ morning";
[formatter setDateFormat:@"EEEE"]; /// EEEE is long format of day of the week see: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
return [NSString stringWithFormat:formatString, [formatter stringFromDate: self]];
}
//formatString = @"on %@ the week before last";
/*if (secondsIntoDay < kOneHour * 2) // after 10pm
formatString = @"early on %@ the week before last";
else if (timeSinceMidnight > kOneHour * 13)
formatString = @"late on %@ the week before last"; // after 11m*/
//if (timeFromNow < kOneWeek * 2)
//{
// [formatter setDateFormat:@"EEE"]; /// EEE is short format of day of the week see: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
// return [NSString stringWithFormat:formatString, [formatter stringFromDate: self]];
//}
if (timeFromNow < kOneWeek * 2)
{
return @"the week before last";
}
NSDateComponents* myComponents = [gregorian components:unitFlags fromDate:self];
int monthsAgo = myComponents.month - todayComponents.month;
int yearsAgo = myComponents.year - todayComponents.year;
if (yearsAgo == 0)
{
if (monthsAgo == 0)
{
if(myComponents.day > 22)
return @"late this month";
if(myComponents.day < 7)
{
if(!earlyMonthStrings)
{
earlyMonthStrings = [[NSArray arrayWithObjects:@"earlier this month",
//@"at the beginning of the month",
@"early this month",
nil] retain];
}
unsigned int index = random() % ([earlyMonthStrings count] - 1);
return [earlyMonthStrings objectAtIndex:index];
}
return @"earlier this month";
}
if (monthsAgo == 1)
{
if(myComponents.day > 22)
return @"late last month";
if(myComponents.day < 7)
return @"early last month";
return @"last month";
}
formatString = @"in %@ this year";
/*if(myComponents.day > 22)
formatString = @"late in %@ this year";
if(myComponents.day < 7)
formatString = @"early in %@ this year";*/
[formatter setDateFormat:@"MMMM"]; /// MMM is longformat of month see: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
return [NSString stringWithFormat:formatString, [formatter stringFromDate: self]];
}
if (yearsAgo == 1)
{
formatString = @"in %@ last year";
/*if(myComponents.day > 22)
formatString = @"late in %@ last year";
if(myComponents.day < 7)
formatString = @"late in %@ last year";*/
[formatter setDateFormat:@"MMM"]; /// MMM is longformat of month see: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
return [NSString stringWithFormat:formatString, [formatter stringFromDate: self]];
}
// int daysAgo = integerSeconds / integerDay;
// Nothing yet...
[formatter setDateStyle:kCFDateFormatterMediumStyle];
//[formatter setTimeStyle:kCFDateFormatterShortStyle];
return [NSString stringWithFormat:@"on %@",[formatter stringFromDate: self]];
}
else
if(timeFromNow > 0) // The future
{
AICLog(kErrorLogEntry, @"FuzzyDates: Time marked as in the future: referenced date is %@, local time is %@", self, [NSDate date]);
return @"moments ago";
}
else
return @"right now"; // this seems unlikely.
return [self description]; // should never get here.
}
抱歉花了这么长时间后这个...
这是基于代码中相当的和人道的日期和时间线。我加入处理的"最后一个星期一,下午5点",因为我喜欢超过x天前。这一处理过去和未来的达数百年。我热衷于国际化方面所以这需要更多的工作,最终。计算都是在当地的时区。
public static class DateTimePretty
{
private const int SECOND = 1;
private const int MINUTE = 60 * SECOND;
private const int HOUR = 60 * MINUTE;
private const int DAY = 24 * HOUR;
private const int WEEK = 7 * DAY;
private const int MONTH = 30 * DAY;
private const int YEAR = 365;
const string now = "just now";
const string secondsFuture = "in {0} seconds", secondsPast = "{0} seconds ago";
const string minuteFuture = "in about a minute", minutePast = "about a minute ago";
const string minutesFuture = "in about {0} minutes", minutesPast = "about {0} minutes ago";
const string hourFuture = "in about an hour", hourPast = "about an hour ago";
const string hoursFuture = "in about {0} hours", hoursPast = "about {0} hours ago";
const string tomorrow = "tomorrow, {0}", yesterday = "yesterday, {0}";
const string nextDay = "{0}", nextWeekDay = "next {0}", lastDay = "last {0}";
//const string daysFuture = "in about {0} days", daysPast = "about {0} days ago";
const string weekFuture = "in about a week", weekPast = "about a week ago";
const string weeksFuture = "in about {0} weeks", weeksPast = "about {0} weeks ago";
const string monthFuture = "in about a month", monthPast = "about a month ago";
const string monthsFuture = "in about {0} months", monthsPast = "about {0} months ago";
const string yearFuture = "in about a year", yearPast = "about a year ago";
const string yearsFuture = "in about {0} years", yearsPast = "about {0} years ago";
const string centuryFuture = "in about a century", centuryPast = "about a century ago";
const string centuriesFuture = "in about {0} centuries", centuriesPast = "about {0} centuries ago";
/// <summary>
/// Returns a pretty version of the provided DateTime: "42 years ago", or "in 9 months".
/// </summary>
/// <param name="dateTime">DateTime in local time format, not Utc</param>
/// <returns>A pretty string</returns>
public static string GetPrettyDate(DateTime dateTime)
{
DateTime dateTimeNow = DateTime.Now;
bool isFuture = (dateTimeNow.Ticks < dateTime.Ticks);
var ts = isFuture ? new TimeSpan(dateTime.Ticks - dateTimeNow.Ticks) : new TimeSpan(dateTimeNow.Ticks - dateTime.Ticks);
double delta = ts.TotalSeconds;
if (delta < 10)
return now;
if (delta < 1 * MINUTE)
return isFuture ? string.Format(secondsFuture, ts.Seconds) : string.Format(secondsPast, ts.Seconds);
if (delta < 2 * MINUTE)
return isFuture ? minuteFuture : minutePast;
if (delta < 45 * MINUTE)
return isFuture ? string.Format(minutesFuture, ts.Minutes) : string.Format(minutesPast, ts.Minutes);
if (delta < 2 * HOUR)
return isFuture ? hourFuture : hourPast;
if (delta < 7 * DAY)
{
string shortTime = DateTimeFormatInfo.CurrentInfo.ShortTimePattern;
string shortWeekdayTime = "dddd, " + shortTime;
int dtDay = (int) dateTime.DayOfWeek;
int nowDay = (int) dateTimeNow.DayOfWeek;
if (isFuture)
{
if (dtDay == nowDay)
{
if (delta < DAY)
return string.Format(hoursFuture, ts.Hours);
else
return string.Format(nextWeekDay, dateTime.ToString(shortWeekdayTime));
}
else if (dtDay - nowDay == 1 || dtDay - nowDay == -6)
return string.Format(tomorrow, dateTime.ToString(shortTime));
else
return string.Format(nextDay, dateTime.ToString(shortWeekdayTime));
}
else
{
if (dtDay == nowDay)
{
if (delta < DAY)
return string.Format(hoursPast, ts.Hours);
else
return string.Format(lastDay, dateTime.ToString(shortWeekdayTime));
}
else if (nowDay - dtDay == 1 || nowDay - dtDay == -6)
return string.Format(yesterday, dateTime.ToString(shortTime));
else
return string.Format(lastDay, dateTime.ToString(shortWeekdayTime));
}
}
//if (delta < 7 * DAY)
// return isFuture ? string.Format(daysFuture, ts.Days) : string.Format(daysPast, ts.Days);
if (delta < 4 * WEEK)
{
int weeks = Convert.ToInt32(Math.Floor((double) ts.Days / 30));
if (weeks <= 1)
return isFuture ? weekFuture : weekPast;
else
return isFuture ? string.Format(weeksFuture, weeks) : string.Format(weeksPast, weeks);
}
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double) ts.Days / 30));
if (months <= 1)
return isFuture ? monthFuture : monthPast;
else
return isFuture ? string.Format(monthsFuture, months) : string.Format(monthsPast, months);
}
// Switch to days to avoid overflow
delta = ts.TotalDays;
if (delta < 100 * YEAR)
{
int years = Convert.ToInt32(Math.Floor((double) ts.TotalDays / 365.25));
if (years <= 1)
return isFuture ? yearFuture : yearPast;
else
return isFuture ? string.Format(yearsFuture, years) : string.Format(yearsPast, years);
}
else
{
int centuries = Convert.ToInt32(Math.Floor((double) ts.TotalDays / 365.2425));
if (centuries <= 1)
return isFuture ? centuryFuture : centuryPast;
else
return isFuture ? string.Format(centuriesFuture, centuries) : string.Format(centuriesPast, centuries);
}
}
}
我不知道为什么你说这将是一个可怕的编码的做法。每个返回串实际上是一个子集的父母设置,所以你可以相当优雅,这样做在一个如果/elseif链。
if timestamp < 5sec
"A moment ago"
elseif timestamp < 5min
"Few minutes ago"
elseif timestamp < 12hr && timestamp < noon
"Today Morning"
...
elseif timestamp < 1week
"Few days ago"
elseif timestamp < 1month
"Few weeks ago"
elseif timestamp < 6month
"Few Months ago"
...
else
"Really really long time ago"
以我的经验这些类型期的发电机不是"模糊"。事实上,他们只是一堆如果声明的基础段时间。例如,任何时候不超过30秒是"的时刻前"360 390天是"就在一年前",等等。这些将使用的目标日期来计算特殊的名字(日,星期三,等等)。抱歉划的一个幻想你了。
不用说,(但是我会说它无论如何)不使用其中的循环,减少365天每年甚至上的366天飞跃年(或者你会发现自己在列明王的开发)
这里是c#版本:
http://tiredblogger.wordpress.com/2008/08/21/creating-twitter-esque-relative-dates-in-c/
我知道表达这样的时代已经变得相当受欢迎最近,但是,请考虑这一选项关直相对'模糊'的日期和正常绝对的日期。
例如,它知道这一评论意见作出5分钟前,但很少有用告诉我的评论一个是4小时前和评论,B为9小时前,当它是11:我宁可知道这一意见,一种是书面的,当有人今天早上醒来的时候和评B是由某人熬夜(假设我知道他们在我的时区).
-- 编辑:寻找更接近你的问题你似乎已经避免这在一定程度通过参照一天的时间,而不是"X前",但另一方面,你可以给人一种虚假的印象,如果用户在不同时区,因为你的"今天早上"可以在晚上相关的用户。
这可能是酷到加强的时代相一天的时间取决于其他用户的时区,但是,假设用户愿意供应,这是正确的。
我是不是满意的解决方案中的其他问题。这么做我自己使用的日期的时间类。海事组织,它的清洁。在我的测试它的工作就像因为我想要的。希望这可以帮助别人。
DateTime now = DateTime.Now;
long nowticks = now.Ticks;
long thenticks = dt.Ticks;
long diff = nowticks - thenticks;
DateTime n = new DateTime(diff);
if (n.Year > 1)
{
return n.Year.ToString() + " years ago";
}
else if (n.Month > 1)
{
return n.Month.ToString() + " months ago";
}
else if (n.Day > 1)
{
return n.Day.ToString() + " days ago";
}
else if (n.Hour > 1)
{
return n.Hour.ToString() + " hours ago";
}
else if (n.Minute > 1)
{
return n.Minute.ToString() + " minutes ago";
}
else
{
return n.Second.ToString() + " seconds ago";
}
这几乎总是使用一个巨大的开关声明和容易执行。
牢记以下几点:
- 总是试验的最小时间跨度的第一个
- 别忘了保持你的串的本地化。
你可以找到 源自timeago 有用的。本说明的是"一个jQuery插件,可以很容易地支持以自动更新的模糊的时间戳(例如"4分钟前"或"约1日前")."
它本质上是一个JavaScript港口的铁路的 distance_of_time_in_words
功能挤进一个jQuery插件。
我的公司 这一点。净库 做一些你想要什么,它并非常灵活的日期时间分析(包括一些格式的相对),但它只有并非相对产出。
检查出来的时辰一Javascript启发日期分析器。
计时支持大多数的日期和时间格式,例如:
Today, Tomorrow, Yesterday, Last Friday, etc
17 August 2013 - 19 August 2013
This Friday from 13:00 - 16.00
5 days ago
Sat Aug 17 2013 18:40:39 GMT+0900 (JST)
2014-11-30T08:15:30-05:30