NSDate 的一些操作(比较、创建、在现有date加减一定时间等)

创建当前时间

  1. NSDate *date = [NSDate date];  

从现在开始的24小时

        NSTimeInterval a_day = 24*60*60;

        NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:a_day];

根据已有日期创建日期

  1. NSTimeInterval a_day = 24*60*60;  
  2. NSDate *date = [NSDate date];  
  3. NSDate *tomorrow = [date addTimeInterval: date];  

日期比较

  1.       BOOL isEqual = [date isEqualToDate:tomorrow];  
  2. f(isEqual){  
  3. NSLog(@"equal");  

//获取较早的日期

  1. NSDate *earlier_date = [tomorrow earlierDate:date];  
  2.   NSLog(@"earlierDate  = %@",earlierDate);  

//较晚的日期

  1. NSDate *laterDate = [tomorrow laterDate:date];  
  2. NSLog(@"laterDate  = %@",laterDate);  

//两个日期之间相隔多少秒

  1. NSTimeInterval secondsInterval= [date timeIntervalSinceDate:tomorrow];  
  2. NSLog(@"secondsInterval=  %lf",secondsInterval);  

 //通过NSCalendar类来创建日期

  1. NSDateComponents *comps = [[NSDateComponentsalloc]init];  
  2. [comps setMonth:01];  
  3. [comps setDay:31];  
  4. [comps setYear:2013];  
  5. NSCalendar *calendar = [[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];  
  6. NSDate *date = [calendar dateFromComponents:comps];  

 //从已有日期获取日期

  1. unsigned units  = NSMonthCalendarUnit|NSDayCalendarUnit|NSYearCalendarUnit;  
  2. NSDateComponents *_comps = [calendar components:units fromDate:date];  
  3. NSInteger month = [_comps month];  
  4. NSInteger year = [_comps year];  
  5. NSInteger day = [_comps day];  
  6. //NSDateFormatter实现日期的输出  
  7. NSDateFormatter *formatter = [[NSDateFormatteralloc]init];  
  8. [formatter setDateStyle:NSDateFormatterFullStyle];//直接输出的话是机器码  
  9. //或者是手动设置样式[formatter setDateFormat:@"yyyy-mm-dd"];  
  10. NSString *dateString = [formatter stringFromDate:date];  
  11. NSLog(@"dateString = %@",dateString);  
  12. NSLog(@"formater = %@",formatter);  

//获取日期格式对象

  1. - (NSDateFormatter *)getDateFormatter {  
  2.     if (dateFormatter == nil) {  
  3.     dateFormatter = [[NSDateFormatter alloc] init];  
  4.     [dateFormatter setDateStyle:NSDateFormatterMediumStyle];  
  5.     [dateFormatter setTimeStyle:NSDateFormatterNoStyle];  
  6.     }  
  7.     return dateFormatter;  
  8. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值