时区日期处理及定时 (NSDate,NSCalendar,NSTimer,NSTimeZone)
NSDate存儲(chǔ)的是世界標(biāo)準(zhǔn)時(shí)(UTC),輸出時(shí)需要根據(jù)時(shí)區(qū)轉(zhuǎn)換為本地時(shí)間
Dates
? ? ? NSDate類提供了創(chuàng)建date,比較date以及計(jì)算兩個(gè)date之間間隔的功能。Date對(duì)象是不可改變的。
? ? ? 如果你要?jiǎng)?chuàng)建date對(duì)象并表示當(dāng)前日期,你可以alloc一個(gè)NSDate對(duì)象并調(diào)用init初始化:
NSDate *now = [[NSDate alloc] init];? ? ? 或者使用NSDate的date類方法來(lái)創(chuàng)建一個(gè)日期對(duì)象。如果你需要與當(dāng)前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更復(fù)雜的calendar或date components對(duì)象。
? ? ? 創(chuàng)建一定時(shí)間間隔的NSDate對(duì)象:
NSTimeInterval secondsPerDay = 24 * 60 * 60; NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay]; NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay]; [tomorrow release]; [yesterday release];? ? ? 使用增加時(shí)間間隔的方式來(lái)生成NSDate對(duì)象:
NSTimeInterval secondsPerDay = 24 * 60 * 60; NSDate *today = [[NSDate alloc] init]; NSDate *tomorrow, *yesterday; tomorrow = [today dateByAddingTimeInterval: secondsPerDay]; yesterday = [today dateByAddingTimeInterval: -secondsPerDay]; [today release];? ? ? 如果要對(duì)NSDate對(duì)象進(jìn)行比較,可以使用isEqualToDate:, compare:, laterDate:和 earlierDate:方法。這些方法都進(jìn)行精確比較,也就是說(shuō)這些方法會(huì)一直精確比較到NSDate對(duì)象中秒一級(jí)。例如,你可能比較兩個(gè)日期,如果他們之間的間隔在一分鐘之內(nèi)則認(rèn)為這兩個(gè)日期是相等的。在這種情況下使用,timeIntervalSinceDate:方法來(lái)對(duì)兩個(gè)日期進(jìn)行比較。下面的代碼進(jìn)行了示例:
if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...NSCalendar & NSDateComponents
? ? ? 日歷對(duì)象封裝了對(duì)系統(tǒng)日期的計(jì)算,包括這一年開(kāi)始,總天數(shù)以及劃分。你將使用日歷對(duì)象對(duì)絕對(duì)日期與date components(包括年,月,日,時(shí),分,秒)進(jìn)行轉(zhuǎn)換。
? ? ? NSCalendar定義了不同的日歷,包括佛教歷,格里高利歷等(這些都與系統(tǒng)提供的本地化設(shè)置相關(guān))。NSCalendar與NSDateComponents對(duì)象緊密相關(guān)。
? ? ? 你可以通過(guò)NSCalendar對(duì)象的currentCalendar方法來(lái)獲得當(dāng)前系統(tǒng)用戶設(shè)置的日歷。
? ? ? usersCalendar和currentCalendar對(duì)象是相等的,盡管他們是不同的對(duì)象。
? ? ? 你可以使用NSDateComponents對(duì)象來(lái)表示一個(gè)日期對(duì)象的組件——例如年,月,日和小時(shí)。如果要使一個(gè)NSDateComponents對(duì)象有意義,你必須將其與一個(gè)日歷對(duì)象相關(guān)聯(lián)。下面的代碼示例了如何創(chuàng)建一個(gè)NSDateComponents對(duì)象:
? ? ? ? 要將一個(gè)日期對(duì)象解析到相應(yīng)的date components,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents對(duì)象返回組件。
NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today]; NSInteger day = [weekdayComponents day]; NSInteger weekday = [weekdayComponents weekday];同樣你也可以從NSDateComponents對(duì)象來(lái)創(chuàng)建NSDate對(duì)象: ?
NSDateComponents *components = [[NSDateComponents alloc] init]; [components setWeekday:2]; // Monday [components setWeekdayOrdinal:1]; // The first Monday in the month [components setMonth:5]; // May [components setYear:2008]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *date = [gregorian dateFromComponents:components];? ? ? 為了保證正確的行為,您必須確保使用的組件在日歷上是有意義的。指定“出界”日歷組件,如一個(gè)-6或2月30日在公歷中的日期值產(chǎn)生未定義的行為。
? ? ? 你也可以創(chuàng)建一個(gè)不帶年份的NSDate對(duì)象,這樣的操作系統(tǒng)會(huì)自動(dòng)生成一個(gè)年份,但在后面的代碼中不會(huì)使用其自動(dòng)生成的年份。
NSDateComponents *components = [[NSDateComponents alloc] init]; [components setMonth:11]; [components setDay:7]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *birthday = [gregorian dateFromComponents:components];下面的示例顯示了如何從一個(gè)日歷置換到另一個(gè)日歷:
1 NSDateComponents *comps = [[NSDateComponents alloc] init]; 2 3 [comps setDay:6]; 4 [comps setMonth:5]; 5 [comps setYear:2004]; 6 7 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 8 9 NSDate *date = [gregorian dateFromComponents:comps]; 10 11 [comps release]; 12 [gregorian release]; 13 14 NSCalendar *hebrew = [[NSCalendar alloc] initWithCalendarIdentifier:NSHebrewCalendar]; 15 16 NSUInteger unitFlags = NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit; 17 18 NSDateComponents *components = [hebrew components:unitFlags fromDate:date]; 19 20 NSInteger day = [components day]; // 15 21 NSInteger month = [components month]; // 9 22 NSInteger year = [components year]; // 5764歷法計(jì)算
? ? 在當(dāng)前時(shí)間加上一個(gè)半小時(shí):
1 NSDate *today = [[NSDate alloc] init]; 2 3 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 4 5 NSDateComponents *offsetComponents = [[NSDateComponents alloc] init]; 6 7 [offsetComponents setHour:1]; 8 [offsetComponents setMinute:30]; 9 10 // Calculate when, according to Tom Lehrer, World War III will end 11 NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];? ? 獲得當(dāng)前星期中的星期天(使用格里高利歷):
1 NSDate *today = [[NSDate alloc] init]; 2 3 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 4 5 // Get the weekday component of the current date 6 NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today]; 7 8 /* 9 Create a date components to represent the number of days to subtract from the current date. 10 11 The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today is Sunday, subtract 0 days.) 12 */ 13 14 NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init]; 15 16 [componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)]; 17 18 NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0]; 19 20 /* 21 Optional step: 22 beginningOfWeek now has the same hour, minute, and second as the original date (today). 23 24 To normalize to midnight, extract the year, month, and day components and create a new date from those components. 25 */ 26 27 NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: beginningOfWeek]; 28 29 beginningOfWeek = [gregorian dateFromComponents:components];?? ? 如何可以計(jì)算出一周的第一天(根據(jù)系統(tǒng)的日歷設(shè)置):
NSDate *today = [[NSDate alloc] init]; NSDate *beginningOfWeek = nil; BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];? ? 獲得兩個(gè)日期之間的間隔:
1 NSDate *startDate = ...; 2 NSDate *endDate = ...; 3 4 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 5 6 NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; 7 8 NSDateComponents *components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0]; 9 10 NSInteger months = [components month]; 11 NSInteger days = [components day];??? 使用Category來(lái)計(jì)算同一時(shí)代(AD|BC)兩個(gè)日期午夜之間的天數(shù):
1 @implementation NSCalendar (MySpecialCalculations) 2 3 -(NSInteger)daysWithinEraFromDate:(NSDate *) startDate toDate:(NSDate *) endDate { 4 NSInteger startDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:startDate]; 5 6 NSInteger endDay=[self ordinalityOfUnit:NSDayCalendarUnit inUnit: NSEraCalendarUnit forDate:endDate]; 7 8 return endDay-startDay; 9 } 10 11 @end? ? 使用Category來(lái)計(jì)算不同時(shí)代(AD|BC)兩個(gè)日期的天數(shù):
1 @implementation NSCalendar (MyOtherMethod) 2 3 -(NSInteger) daysFromDate:(NSDate *) startDate toDate:(NSDate *) endDate { 4 5 NSCalendarUnit units=NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; 6 7 NSDateComponents *comp1=[self components:units fromDate:startDate]; 8 NSDateComponents *comp2=[self components:units fromDate endDate]; 9 10 [comp1 setHour:12]; 11 [comp2 setHour:12]; 12 13 NSDate *date1=[self dateFromComponents: comp1]; 14 NSDate *date2=[self dateFromComponents: comp2]; 15 16 return [[self components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0] day]; 17 } 18 19 @end判斷一個(gè)日期是否在當(dāng)前一周內(nèi)(使用格里高利歷):
1 -(BOOL)isDateThisWeek:(NSDate *)date { 2 3 NSDate *start; 4 NSTimeInterval extends; 5 6 NSCalendar *cal=[NSCalendar autoupdatingCurrentCalendar]; 7 NSDate *today=[NSDate date]; 8 9 BOOL success= [cal rangeOfUnit:NSWeekCalendarUnit startDate:&start interval: &extends forDate:today]; 10 11 if(!success) 12 return NO; 13 14 NSTimeInterval dateInSecs = [date timeIntervalSinceReferenceDate]; 15 NSTimeInterval dayStartInSecs= [start timeIntervalSinceReferenceDate]; 16 17 if(dateInSecs > dayStartInSecs && dateInSecs < (dayStartInSecs+extends)){ 18 return YES; 19 } 20 else { 21 return NO; 22 } 23 }1、獲取當(dāng)前時(shí)間
另外的方法:
1 -(NSString *)getDate 2 { 3 NSDateFormatter*formatter = [[NSDateFormatteralloc] init]; 4 [formatter setDateFormat:@"yyyy-MM-dd EEEE HH:mm:ss a"]; 5 NSString *locationString=[formatter stringFromDate: [NSDate date]]; 6 [formatter release]; 7 return locationString; 8 }//大寫的H日期格式將默認(rèn)為24小時(shí)制,小寫的h日期格式將默認(rèn)為12小時(shí)
//不需要特別設(shè)置,只需要在dataFormat里設(shè)置類似"yyyy-MMM-dd"這樣的格式就可以了
?
日期格式如下:
y ?年 ?Year ?1996; 96 ?
M ?年中的月份 ?Month ?July; Jul; 07 ?
w ?年中的周數(shù) ?Number ?27 ?
W ?月份中的周數(shù) ?Number ?2 ?
D ?年中的天數(shù) ?Number ?189 ?
d ?月份中的天數(shù) ?Number ?10 ?
F ?月份中的星期 ?Number ?2 ?
E ?星期中的天數(shù) ?Text ?Tuesday; Tue ?
a ?Am/pm 標(biāo)記 ?Text ?PM ?
H ?一天中的小時(shí)數(shù)(0-23) ?Number ?0 ?
k ?一天中的小時(shí)數(shù)(1-24) ?Number ?24 ?
K ?am/pm 中的小時(shí)數(shù)(0-11) ?Number ?0 ?
h ?am/pm 中的小時(shí)數(shù)(1-12) ?Number ?12 ?
m ?小時(shí)中的分鐘數(shù) ?Number ?30 ?
s ?分鐘中的秒數(shù) ?Number ?55 ?
S ?毫秒數(shù) ?Number ?978 ?
z ?時(shí)區(qū) ?General time zone ?Pacific Standard Time; PST; GMT-08:00 ?
Z ?時(shí)區(qū) ?RFC 822 time zone ?-0800
?
2、NSTimer定時(shí)器的基本操作方式
NSTimer是Cocoa中比較常用的定時(shí)器類,基本操作如下:
handleTimer方法可以自行定義。在需要的地方創(chuàng)建timer即可,handleTimer就可以每0.5秒執(zhí)行一次。
1 - (void) handleTimer: (NSTimer *) timer 2 { 3 //在這里進(jìn)行處理 4 } 5 NSTimer *timer; 6 timer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(handleTimer:)userInfo: nil repeats: YES];?3、定時(shí)器
設(shè)置定時(shí)器下面顯示的定時(shí)器將在一秒鐘后觸發(fā),并一直重復(fù)直到定時(shí)器被禁用。定時(shí)器每次激活時(shí),就會(huì)調(diào)用發(fā)送選擇器消息的目標(biāo)來(lái)進(jìn)行初始化。回調(diào)方法帶有一個(gè)參數(shù),就是定時(shí)器本身.要禁用一個(gè)定時(shí)器,給它發(fā)送invalidate消息,這將釋放定時(shí)器對(duì)象并把它從當(dāng)前運(yùn)行循環(huán)中刪除。
1 NSTime *timer ; 2 timer = [NSTimer scheduledTimerWithTimeInterval:1.0target:self selector:@selector(handlTimer:) userInfo:nilrepeats:YES]; 3 4 - (void)handleTimer:(NSTimer *)timer{ 5 printf("timer count: %d", count++); 6 if(count > 3) 7 { 8 [timer invalidate]; 9 }1. 使用 NSTimeZone 取得世界各地時(shí)間的方法
?下列程式碼將示范,如何利用 NSTimeZone 取得世界上已知的時(shí)區(qū)名稱,并且透過(guò)這些名稱來(lái)獲得當(dāng)?shù)貢r(shí)間,如果在系統(tǒng)時(shí)間的取得上有任何疑問(wèn),可以參考取得 iOS 系統(tǒng)日期與星期的方法一文,其程式碼如下。
1 //取得目前已知的所有地里名稱 2 NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames]; 3 4 //取得本地目前時(shí)間 5 NSDate *date = [NSDate date]; 6 7 for(NSString *name in timeZoneNames) { 8 NSTimeZone *timezone = [[NSTimeZone alloc] initWithName:name]; 9 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 10 11 //設(shè)定時(shí)間格式 12 [formatter setDateFormat:@"YYYY-MM-d HH:mm:ss"]; 13 14 //設(shè)定時(shí)區(qū) 15 [formatter setTimeZone:timezone]; 16 17 //時(shí)間格式正規(guī)化并做時(shí)區(qū)校正 18 NSString *correctDate = [formatter stringFromDate:date]; 19 20 NSLog(@"地點(diǎn):%@ 當(dāng)?shù)貢r(shí)間:%@",[timezone name], correctDate); 21 22 [formatter release]; 23 [timezone release]; 24 }? 由于能取得的地點(diǎn)相當(dāng)多,下圖只是部份的執(zhí)行結(jié)果。
?
2. 取得 iOS 系統(tǒng)日期與星期的方法
?
在之前的文章中已經(jīng)說(shuō)明如何取得 Device 里的 iOS 系統(tǒng)時(shí)間,在此將在示范如何使用 NSDate 取得系統(tǒng)的日期與星期,請(qǐng)看以下程式碼
1 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 2 NSDate *date = [NSDate date]; 3 4 //正規(guī)化的格式設(shè)定 5 [formatter setDateFormat:@"YYYY-MM-dd' 'EEEE"]; 6 7 //正規(guī)化取得的系統(tǒng)時(shí)間并顯示 8 dateLabel.text = [formatter stringFromDate:date];當(dāng)然 NSFormatter 能正規(guī)化的格式不只這些,想知道其他的參數(shù)可以參考關(guān)于 NSDateFormatter 的二三事一文。
3. 取得 iOS 系統(tǒng)時(shí)間的方法
如何取得 Device 里的 iOS 系統(tǒng)時(shí)間,可以參考以下程式碼。
1 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 2 NSDate *date = [NSDate date]; 3 4 //正規(guī)化的格式設(shè)定 5 [formatter setTimeStyle:NSDateFormatterFullStyle]; 6 7 //正規(guī)化取得的系統(tǒng)時(shí)間并顯示 8 timeLabel.text = [formatter stringFromDate:date]; 9 10 [formatter release];?在時(shí)間格式正規(guī)化的部份也有多種樣式可供選擇,其樣式如下。
最后,如果要讓時(shí)間與現(xiàn)實(shí)時(shí)間同步可以考慮實(shí)做計(jì)時(shí)器 Timer 來(lái)解決此問(wèn)題,詳細(xì)的設(shè)定方式可參閱 Timer / 計(jì)時(shí)器的基本使用方法。
4. Timer / 計(jì)時(shí)器的基本使用方法
?這里介紹 Timer 的基本使用方法,首先設(shè)定 Timer 的相關(guān)的參數(shù),程式碼如下。(View-based Template)
1 //自行定義的函式,用來(lái)設(shè)定使用Timer/計(jì)時(shí)器的相關(guān)參數(shù) 2 -(void)initializeTimer { 3 4 //設(shè)定Timer觸發(fā)的頻率,每秒30次 5 float theInterval = 1.0/30.0; 6 fpsLabel.text = [NSString stringWithFormat:@"%0.3f", theInterval]; 7 8 //正式啟用Timer,selector是設(shè)定Timer觸發(fā)時(shí)所要呼叫的函式 9 [NSTimer scheduledTimerWithTimeInterval:theInterval 10 target:self 11 selector:@selector(countTotalFrames:) 12 userInfo:nil 13 repeats:YES]; 14 }???上述程式碼,已經(jīng)完成 Timer 的基本設(shè)定,而下列程式碼則是 Timer 觸發(fā)時(shí)所呼叫的函式寫法。
1 -(void)countTotalFrames:(NSTimer *)theTimer { 2 frameCount ++; 3 framesLabel.text = [NSString stringWithFormat:@"%d", frameCount]; 4 }?最后,別忘記在程式進(jìn)入點(diǎn)這邊要呼叫自行定義的 initializeTimer 函式,才能讓 Timer 運(yùn)作。
轉(zhuǎn)載于:https://www.cnblogs.com/tryingx/articles/3720606.html
總結(jié)
以上是生活随笔為你收集整理的时区日期处理及定时 (NSDate,NSCalendar,NSTimer,NSTimeZone)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 郑州银行信用卡电话多少?郑州银行相关联系
- 下一篇: 表单的get和post使用情景