1、获取当前时间和之前某时间点的时间差:
+ dateWithTimeIntervalSinceNow:
+ dateWithTimeInterval:sinceDate:
+ dateWithTimeIntervalSinceReferenceDate:
+ dateWithTimeIntervalSince1970:
以上4个方法可获得。
2、获取当前时间:
+ date:
比如:
// get current date/time
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// display in 12HR/24HR (i.e. 11:25PM or 23:25) format according to User Settings
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
NSString *currentTime = [dateFormatter stringFromDate:today];
[dateFormatter release];
NSLog(@”User’s current time in their preference format:%@”,currentTime);
打印出来只有time没有date,并且格式很不爽,因为setTimeStyle:NSDateFormatterShortStyle
于是看文档,一共5种:
typedef enum {
NSDateFormatterNoStyle = kCFDateFormatterNoStyle,
NSDateFormatterShortStyle = kCFDateFormatterShortStyle,
NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle,
NSDateFormatterLongStyle = kCFDateFormatterLongStyle,
NSDateFormatterFullStyle = kCFDateFormatterFullStyle
} NSDateFormatterStyle;
总之这5种格式都特坑爹,而且貌似要么setTime要么setDate。并且还都是GMT时间!
关于时区问题,有这么个方法:
- (NSString *)descriptionWithLocale:(id)locale
然后需要填locale的时候不知道id该怎么写,如果写
NSDate *today = [[NSDate date] descriptionWithLocale:[NSLocale currentLocale]];
的话出警告,并且没效果。至于它怎么弄才对,我懒的管了。
其实用这个方法特好: [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
直接生成想要的字符串了,什么style都是浮云,format各种自定义好用到爆⋯⋯
这样就可以根据时间生成字符串了⋯⋯
PS:我好像是在各种搬运苹果的文档⋯⋯
更新:
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
这行代码里的小时H如果大写是24小时制,如果h小写是12小时制。