Mar*_*rio 6 iphone objective-c nsdate nscalendar ios
我的应用程序显示消息列表,每个消息都有一个创建日期.
我不想只显示日期,而是根据创建日期过去的时间显示不同的格式.
例如,这是我从日期创建日期字符串的方式:
NSDate *date = someMessage.creationDate;
NSTimeInterval timePassed = [[NSDate date] timeIntervalSinceDate:date];
if (timePassed < 60 ) { // less then one minute
return @"now"
} else if (timePassed < 3600) { // less then one hour
NSInteger minutes = (NSInteger) floor(timePassed / 60.0);
return [NSString stringWithFormat:@"%d minutes ago", minutes];
}
Run Code Online (Sandbox Code Playgroud)
所以现在我想添加以下案例:
else if ("timePassed < 24 hours ago and within the same calendar day")
// do something
} else if ("timePassed > 24 hours, or within previous calendar day") {
// do something else
}
Run Code Online (Sandbox Code Playgroud)
但不知道该怎么做,任何帮助将不胜感激
这是一个简单的类别,NSDate它添加了有用的日期比较方法:
#ifndef SecondsPerDay
#define SecondsPerDay 86400
#endif
@interface NSDate (Additions)
/**
* This method returns the number of days between this date and the given date.
*/
- (NSUInteger)daysBetween:(NSDate *)date;
/**
* This method compares the dates without time components.
*/
- (NSComparisonResult)timelessCompare:(NSDate *)date;
/*
* This method returns a new date with the time set to 12:00 AM midnight local time.
*/
- (NSDate *)dateWithoutTimeComponents;
@end
@implementation NSDate (Additions)
- (NSUInteger)daysBetween:(NSDate *)date
{
NSDate *dt1 = [self dateWithoutTimeComponents];
NSDate *dt2 = [date dateWithoutTimeComponents];
return ABS([dt1 timeIntervalSinceDate:dt2] / SecondsPerDay);
}
- (NSComparisonResult)timelessCompare:(NSDate *)date
{
NSDate *dt1 = [self dateWithoutTimeComponents];
NSDate *dt2 = [date dateWithoutTimeComponents];
return [dt1 compare:dt2];
}
- (NSDate *)dateWithoutTimeComponents
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit
fromDate:self];
return [calendar dateFromComponents:components];
}
@end
Run Code Online (Sandbox Code Playgroud)
NSDate *currentDate = [NSDate date];
NSDate *distantPastDate = [NSDate distantPast];
NSComparisonResult *result = [currentDate timelessCompare:distantPastDate];
// result will equal NSOrderedDescending
Run Code Online (Sandbox Code Playgroud)
你需要知道两个日期到第二个日期之间的区别吗?使用timeIntervalSinceDate:标准配置NSDate.
您一定会想看看这个答案。
即:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:yourDate];
NSUInteger year = [components year];
NSUInteger dayOfYear = [[NSCalendar currentCalendar] ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:yourDate];
Run Code Online (Sandbox Code Playgroud)
检查day两个 NSDate 的该属性,然后您就会知道它们是否在同一日历日。至于 24 小时或更短/更长,您可以取一个日期并使用该函数timeIntervalSinceDate:,看看它是否大于/小于 86400(一天中的秒数)。
编辑:更新为更具体的年份和年份检查。
| 归档时间: |
|
| 查看次数: |
2541 次 |
| 最近记录: |