如何在Objective-C中格式化日期,类似于jquery.timeago库? [英] How can I format a date in Objective-C similar to the jquery.timeago library?
问题描述
我有一个显示在表格单元格中的项目,其中一部分是过去的日期/时间戳。
I have a feed of items displayed in table cells, part of which is a date / timestamp in the past.
在Objective-C中,我如何以与 jquery.timeago插件?
In Objective-C, how can I accomplish formatting them in the same manner as the jquery.timeago plugin on the web?
即接收日期并输出如下内容:
That is, taking in a date and outputting things like:
- 'just now'
- '2分钟前'
- '24天前'
- '一个月前'
- 'just now'
- '2 minutes ago'
- '24 days ago'
- 'a month ago'
我看到有 NSDate扩展类,其中包含dateWithDaysBeforeNow,dateWithMinutesBeforeNow等方法,但是如果有一个库已经完成了我将使用它。
I see there is an NSDate extension class here with methods such as dateWithDaysBeforeNow, dateWithMinutesBeforeNow, etc, but if there is a library out there that has already done this I will use it.
编辑:除此之外,如果某人编写了一个方法(通过这个链接的扩展库或其他方法获取日期,返回一个完成此操作的字符串),我将奖励他们答案。
Further to this, if someone composes a method (takes a date, returns a string) that accomplishes this, either with this linked extensions library or another method, I will award them the answer.
ED IT 2 Bounty适用于任何可以在Objective-C中编写模糊日期算法的人。
EDIT 2 Bounty goes to whoever can write the fuzzy date algorithm in Objective-C.
推荐答案
创建静态类方法:
+ (NSString *)stringForTimeIntervalSinceCreated:(NSDate *)dateTime serverTime:(NSDate *)serverDateTime{
NSInteger MinInterval;
NSInteger HourInterval;
NSInteger DayInterval;
NSInteger DayModules;
NSInteger interval = abs((NSInteger)[dateTime timeIntervalSinceDate:serverDateTime]);
if(interval >= 86400)
{
DayInterval = interval/86400;
DayModules = interval%86400;
if(DayModules!=0)
{
if(DayModules>=3600){
//HourInterval=DayModules/3600;
return [NSString stringWithFormat:@"%i days", DayInterval];
}
else {
if(DayModules>=60){
//MinInterval=DayModules/60;
return [NSString stringWithFormat:@"%i days", DayInterval];
}
else {
return [NSString stringWithFormat:@"%i days", DayInterval];
}
}
}
else
{
return [NSString stringWithFormat:@"%i days", DayInterval];
}
}
else{
if(interval>=3600)
{
HourInterval= interval/3600;
return [NSString stringWithFormat:@"%i hours", HourInterval];
}
else if(interval>=60){
MinInterval = interval/60;
return [NSString stringWithFormat:@"%i minutes", MinInterval];
}
else{
return [NSString stringWithFormat:@"%i Sec", interval];
}
}
}
这篇关于如何在Objective-C中格式化日期,类似于jquery.timeago库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!