Objective-c_Date 日期对象

本文详细介绍了NSDate的基本用法,包括创建不同类型的NSDate实例、日期与时间的转换、日期格式化及字符串转换,以及如何进行日期比较等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 NSDate *date = [NSDate date];

        NSLog(@"%@",date);

        NSLog(@"%@",[date descriptionWithLocale:[NSLocale currentLocale]]);

        

        NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:60*60*12];

        NSLog(@"%@",[date1 descriptionWithLocale:[NSLocale currentLocale]]);

        

        NSDate *date2 = [NSDate distantFuture];

        NSLog(@"%@",date2);

         NSLog(@"%@",[date2 descriptionWithLocale:[NSLocale currentLocale]]);

        

        NSDate *date3 = [NSDate distantPast];

      NSLog(@"%@",[date3 descriptionWithLocale:[NSLocale currentLocale]]);

        

        //NSDate的比较

        NSDate *later= [date3 laterDate:date2];

         NSLog(@"%@",[later descriptionWithLocale:[NSLocale currentLocale]]);

        

        NSDate *earlier = [date3 earlierDate:date2];

        NSLog(@"%@",[earlier descriptionWithLocale:[NSLocale currentLocale]]);

        

        

        

        NSTimeInterval sc = [date timeIntervalSinceNow];

        NSDate *currentDate = [[NSDate alloc]initWithTimeIntervalSinceNow:sc];

        NSLog(@"%@",currentDate);

        

        

        //NSDate和字符串的转换

        NSDateFormatter *df = [[NSDateFormatter alloc]init];

        df.dateFormat = @"yyyy-MM-dd hh:mm:ss";

        //[df setDateFormat:@"yyyyMMdd  HH小时mmss"];

        NSString *na = [df stringFromDate:date];

        NSLog(@"系统当前时间为:%@",na);

        

        //取出日期中的年、月、日、时、分、秒

        NSCalendarDate *calendar = [NSCalendarDate calendarDate];

        int year = [calendar yearOfCommonEra];

        int month = [calendar monthOfYear];

        int day = [calendar dayOfMonth];

        NSLog(@"%4d-%02d-%02d",year,month,day);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值