NSDate 时间比较...等

http://blog.csdn.net/reylen/article/details/8560128

创建当前时间
NSDate *date = [NSDate date]; 从现在开始的24小时
NSTimeInterval a_day = **;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:a_day];
根据已有日期创建日期
[cpp] view plain copy print?
NSTimeInterval a_day = **;
NSDate *date = [NSDate date];
NSDate *tomorrow = [date addTimeInterval: date];
日期比较
[cpp] view plain copy print?
BOOL isEqual = [date isEqualToDate:tomorrow];
f(isEqual){
NSLog(@"equal"); //获取较早的日期
[cpp] view plain copy print?
NSDate *earlier_date = [tomorrow earlierDate:date];
NSLog(@"earlierDate = %@",earlierDate); //较晚的日期
[cpp] view plain copy print?
NSDate *laterDate = [tomorrow laterDate:date];
NSLog(@"laterDate = %@",laterDate); //两个日期之间相隔多少秒
[cpp] view plain copy print?
NSTimeInterval secondsInterval= [date timeIntervalSinceDate:tomorrow];
NSLog(@"secondsInterval= %lf",secondsInterval); //通过NSCalendar类来创建日期
[cpp] view plain copy print?
NSDateComponents *comps = [[NSDateComponentsalloc]init];
[comps setMonth:];
[comps setDay:];
[comps setYear:];
NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [calendar dateFromComponents:comps]; //从已有日期获取日期
[cpp] view plain copy print?
unsigned units = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;
NSDateComponents *_comps = [calendar components:units fromDate:date];
NSInteger month = [_comps month];
NSInteger year = [_comps year];
NSInteger day = [_comps day]; //NSDateFormatter实现日期的输出
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
[formatter setDateStyle:NSDateFormatterFullStyle];//直接输出的话是机器码
//或者是手动设置样式[formatter setDateFormat:@"yyyy-mm-dd"];
NSString *dateString = [formatter stringFromDate:date];
NSLog(@"dateString = %@",dateString);
NSLog(@"formater = %@",formatter); //获取日期格式对象
[cpp] view plain copy print?
- (NSDateFormatter *)getDateFormatter {
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
}
return dateFormatter;
}

时间比较

-(int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
int ci;
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1 = [df dateFromString:date01];
dt2 = [df dateFromString:date02];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
//date02比date01大
case NSOrderedAscending: ci=; break;
//date02比date01小
case NSOrderedDescending: ci=-; break;
//date02=date01
case NSOrderedSame: ci=; break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
}
return ci;
}
上一篇:centos7 docker升级到最新稳定版本


下一篇:日志文件清理工具V1.1