Objective-C 中的日期和时间



NNSDate 和 NSDateFormatter 类提供了日期和时间特性。

NSDateFormatter 是一个帮助类,可轻松将 NSDate 转换为 NSString,反之亦然。

下面显示了一个简单的示例,展示了如何将 NSDate 转换为 NSString,再转换为 NSDate。

#import <Foundation/Foundation.h>

int main() {
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   NSDate *date= [NSDate date];
   NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
   [dateFormatter setDateFormat:@"yyyy-MM-dd"];
   
   NSString *dateString = [dateFormatter stringFromDate:date];
   NSLog(@"Current date is %@",dateString);
   NSDate *newDate = [dateFormatter dateFromString:dateString];
   NSLog(@"NewDate: %@",newDate);
   
   [pool drain]
   return 0;
}

现在,当我们编译并运行程序时,我们将获得以下结果。

2013-09-29 14:48:13.445 Date and time[870] Current date is 2013-09-29
2013-09-29 14:48:13.447 Date and time[870] NewDate: 2013-09-28 18:30:00 +0000

如我们在上面的程序中所看到的,我们借助 NSDate 获取当前时间。

NSDateFormatter 类负责转换格式。

可以根据可用的数据来更改日期格式。例如,当我们希望在上面的示例中添加时间时,日期格式可以更改为 @"yyyy-MM-dd:hh:mm:ss"

objective_c_foundation_framework.htm
广告
© . All rights reserved.