object-c基礎語法NSDate, 主要學習NSDate的設置、獲取當前時間、當前時間加減秒後的時間、日期比較、日期轉換成NSString等
XCode4.6.3,OS X SDK 10.8; NSDate日期操作,獲取當前日期,日期比較,日期格式,日期推算,時差解決辦法等 。
一、NSDate初始化
// 獲取當前日期
NSDate *date = [NSDate date];
// 打印結果: 當前時間 date = 2013-08-16 09:00:04 +0000
NSLog(@"當前時間 date = %@",date);
// 獲取從某個日期開始往前或者往後多久的日期,此處60代表60秒,如果需要獲取之前的,將60改爲-60即可
date = [[NSDate alloc] initWithTimeInterval:60 sinceDate:[NSDate date]];
//打印結果:當前時間 往後60s的時間date = 2013-08-16 09:01:04 +0000
NSLog(@"當前時間 往後60s的時間date = %@",date);
PS:測試時時間是下午5點,但是得到的當前時間卻是上午9點,相差了8小時,是時區的問題
解決辦法:
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localDate = [date dateByAddingTimeInterval: interval];
// 打印結果 正確當前時間 localDate = 2013-08-16 17:01:04 +0000
NSLog(@"正確當前時間 localDate = %@",localDate);
二、NSDate與NSString的轉換
/*---- NSDate與NSString----*/
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
// 設置日期格式
[dateFormatter setDateFormat:@"年月日 YYYY/mm/dd 時間 hh:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
// 打印結果:dateString = 年月日 2013/10/16 時間 05:15:43
NSLog(@"dateString = %@",dateString);
// 設置日期格式
[dateFormatter setDateFormat:@"YYYY-MM-dd"];
NSString *year = [dateFormatter stringFromDate:[NSDate date]];
// 打印結果:年月日 year = 2013-08-16
NSLog(@"年月日 year = %@",year);
// 設置時間格式
[dateFormatter setDateFormat:@"hh:mm:ss"];
NSString *time = [dateFormatter stringFromDate:[NSDate date]];
// 打印結果:時間 time = 05:15:43
NSLog(@"時間 time = %@",time);
三、日期的比較
/*----日期時間的比較----*/
// 當前時間
NSDate *currentDate = [NSDate date];
// 比當前時間晚一個小時的時間
NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]];
// 比當前時間早一個小時的時間
NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]];
// 比較哪個時間遲
if ([currentDate laterDate:laterDate]) {
// 打印結果:current-2013-08-16 09:25:54 +0000比later-2013-08-16 10:25:54 +0000晚
NSLog(@"current-%@比later-%@晚",currentDate,laterDate);
}
// 比較哪個時間早
if ([currentDate earlierDate:earlierDate]) {
// 打印結果:current-2013-08-16 09:25:54 +0000 比 earlier-2013-08-16 08:25:54 +0000
NSLog(@"current-%@ 比 earlier-%@ 早",currentDate,earlierDate);
}
if ([currentDate compare:earlierDate]==NSOrderedDescending) {
// 打印結果
NSLog(@"current 晚");
}
if ([currentDate compare:currentDate]==NSOrderedSame) {
// 打印結果
NSLog(@"時間相等");
}
if ([currentDate compare:laterDate]==NSOrderedAscending) {
// 打印結果
NSLog(@"current 早");
}