本文主要是介绍NSDate分类-日期格式化以及日期常用判断,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- NSDate+LC.h
@interface NSDate (LC)/// 是否为今天
- (BOOL)isToday;/// 是否为昨天
- (BOOL)isYesterday;/// 是否为今年
- (BOOL)isThisYear;/// 返回年月日
- (NSDate *)dateWithYMD;/// 获得与当前时间的差距
- (NSDateComponents *)deltaWithNow;/// 返回日期字符串
- (NSString *)dateString;
@end
- NSDate+LC.m
#import "NSDate+LC.h"@implementation NSDate (LC)/// 是否为今天
- (BOOL)isToday
{NSCalendar *calendar = [NSCalendar currentCalendar];int unit = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear;// 1.获得当前时间的年月日NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];// 2.获得self的年月日NSDateComponents *selfCmps = [calendar components:unit fromDate:self];return(selfCmps.year == nowCmps.year) &&(selfCmps.month == nowCmps.month) &&(selfCmps.day == nowCmps.day);
}
- (BOOL)isYesterday
{NSDate *nowDate = [[NSDate date] dateWithYMD];NSDate *selfDate = [self dateWithYMD];// 获得nowDate和selfDate的差距NSCalendar *calendar = [NSCalendar currentCalendar];NSDateComponents *cmps = [calendar components:NSCalendarUnitDay fromDate:selfDate toDate:nowDate options:0];return cmps.day == 1;
}/// 返回年月日
- (NSDate *)dateWithYMD
{NSDateFormatter *fmt = [[NSDateFormatter alloc] init];fmt.dateFormat = @"yyyy-MM-dd";NSString *selfStr = [fmt stringFromDate:self];return [fmt dateFromString:selfStr];
}/// 是否为今年
- (BOOL)isThisYear
{NSCalendar *calendar = [NSCalendar currentCalendar];int unit = NSCalendarUnitYear;// 1.获得当前时间的年月日NSDateComponents *nowCmps = [calendar components:unit fromDate:[NSDate date]];// 2.获得self的年月日NSDateComponents *selfCmps = [calendar components:unit fromDate:self];return nowCmps.year == selfCmps.year;
}- (NSDateComponents *)deltaWithNow
{NSCalendar *calendar = [NSCalendar currentCalendar];int unit = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;return [calendar components:unit fromDate:self toDate:[NSDate date] options:0];
}
- (NSString *)dateString
{NSDateFormatter *fmt = [[NSDateFormatter alloc] init];//判断时间 和 现在时间 的差距if (self.isToday) { // 今天if (self.deltaWithNow.hour >= 1) {return [NSString stringWithFormat:@"%d小时前", (int)self.deltaWithNow.hour];} else if (self.deltaWithNow.minute >= 1) {return [NSString stringWithFormat:@"%d分钟前", (int)self.deltaWithNow.minute];} else {return @"刚刚";}} else if (self.isYesterday) { // 昨天fmt.dateFormat = @"昨天 HH:mm";return [fmt stringFromDate:self];} else if (self.isThisYear) { // 今年(至少是前天)fmt.dateFormat = @"MM-dd HH:mm";return [fmt stringFromDate:self];} else { // 非今年fmt.dateFormat = @"yyyy-MM-dd HH:mm";return [fmt stringFromDate:self];}
}
@end
这篇关于NSDate分类-日期格式化以及日期常用判断的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!