iOS中NSDate的一些小例子

Objective-C为处理日期,时间提供了NSDate,NSCalendar对象,还提供了日期格式器来处理日期与字符串之间的转换。

本文主要介绍NSDate。

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        //获取当前日期,时间的NSDate
        NSDate* date1 = [NSDate date];
        NSLog(@"%@",date1);
        
        //获取当前时间开始,一天之后的时间
        NSDate* date2 = [[NSDate alloc] initWithTimeIntervalSinceNow:3600*24];
        NSLog(@"%@",date2);
        
        //获取从当前时间开始,三天之前的日期
        NSDate* date3 = [[NSDate alloc] initWithTimeIntervalSinceNow:-3*3600*24];
        NSLog(@"%@",date3);
        
        //获取从1970年1.1开始,20年之后的日期
        NSDate* date4 = [[NSDate alloc] initWithTimeIntervalSince1970:20*366*3600*24];
        NSLog(@"%@",date4);
        
        //获取系统当前的Locale
        NSLocale* cn = [NSLocale currentLocale];
        NSLog(@"%@",[date1 descriptionWithLocale:cn]);
        
        //获取两个日期之间较早的日期
        NSDate* earlier = [date1 earlierDate:date2];
        NSLog(@"earlier:%@",earlier);
        
        //获取两个日期之间较晚的日期
        NSDate* later = [date1 laterDate:date2];
        NSLog(@"later:%@",later);
        
        //比较两个日期,compare:方法返回NSComparisonResult枚举值
        //该枚举类型包含NSOrderedAscending,NSOrderedSame,NSOrderedDescending三个值
        switch ([date1 compare:date3]) {
            case NSOrderedAscending:
                NSLog(@"date1位于date3之前");
                break;
            case NSOrderedSame:
                NSLog(@"date1与date3日期相等");
                break;
            case NSOrderedDescending:
                NSLog(@"date1位于date3之后");
                break;
                
            default:
                break;
        }
        
        //获取两个时间之间的时间差,秒
        NSLog(@"date1与date3之间差%g秒",[date1 timeIntervalSinceDate:date3]);
        
        //获取指定时间与现在时间的时间差
        NSLog(@"date2与现在时间的时间差为:%g",[date3 timeIntervalSinceNow]);
        
        
        
    }
    return 0;
}

其对应的答应日志如下:

2014-08-26 00:27:56.551 NSDateTest[569:303] 2014-08-25 16:27:56 +0000

2014-08-26 00:27:56.552 NSDateTest[569:303] 2014-08-26 16:27:56 +0000

2014-08-26 00:27:56.552 NSDateTest[569:303] 2014-08-22 16:27:56 +0000

2014-08-26 00:27:56.552 NSDateTest[569:303] 1990-01-16 00:00:00 +0000

2014-08-26 00:27:56.553 NSDateTest[569:303] 2014826 星期二 中国标准时间上午12:27:56

2014-08-26 00:27:56.554 NSDateTest[569:303] earlier:2014-08-25 16:27:56 +0000

2014-08-26 00:27:56.554 NSDateTest[569:303] later:2014-08-26 16:27:56 +0000

2014-08-26 00:27:56.554 NSDateTest[569:303] date1位于date3之后

2014-08-26 00:27:56.555 NSDateTest[569:303] date1date3之间差259200

2014-08-26 00:27:56.555 NSDateTest[569:303] date2与现在时间的时间差为:-259200

Program ended with exit code: 0


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值