ios日期格式大全

1、如何如何將一個字符串如“ 20110826134106”裝化爲任意的日期時間格式,下面列舉兩種類型:

   NSString* string = @"20110826134106";

    NSDateFormatter *inputFormatter = [[[NSDateFormatter allocinitautorelease];

    [inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];

    NSDate* inputDate = [inputFormatter dateFromString:string];

    NSLog(@"date = %@", inputDate);

    

    NSDateFormatter *outputFormatter = [[[NSDateFormatter allocinitautorelease]; 

    [outputFormatter setLocale:[NSLocale currentLocale]];

    [outputFormatter setDateFormat:@"yyyyMMdd HHmmss"];

    NSString *str = [outputFormatter stringFromDate:inputDate];

    NSLog(@"testDate:%@", str);

兩次打印的結果爲:

    date = 2011-08-26 05:41:06 +0000

    testDate:20110826 134106

/*



            NSDateFormatter *dateFormatter=[[NSDateFormatteralloc]init];

            [dateFormatter setDateFormat:@"yyyy"];

            NSString *Str=[dateFormatter stringFromDate:[NSDate date]];

            [dateFormatter release];

            NSDateFormatter *dateFormatter1=[[NSDateFormatteralloc]init];

            [dateFormatter1 setDateFormat:@"MM"];

            NSString *Str1=[dateFormatter1 stringFromDate:[NSDate date]];

            [dateFormatter1 release];

            NSDateFormatter *dateFormatter2=[[NSDateFormatteralloc]init];

            [dateFormatter2 setDateFormat:@"dd"];

            NSString *Str3=[dateFormatter2 stringFromDate:[NSDate date]];

            

            [dateFormatter2 release];

            NSString *dateStr=[NSStringstringWithFormat:@"%@-%@-%@ 00:00:00",Str,Str1,Str3];

            NSLog(@"dateStr------------%@",dateStr);

            //將傳入時間轉換成需要的格式

            NSDateFormatter *format=[[NSDateFormatteralloc]init];

            //[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];//location設置爲中國

            

           // [format setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];//location設置爲中國

            [format setLocale:[NSLocalecurrentLocale]];



            [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

            NSDate *inputDate=[[format dateFromString:dateStr] retain];

            NSTimeZone *fromzone = [NSTimeZonesystemTimeZone];

            NSInteger frominterval = [fromzonesecondsFromGMTForDate: inputDate];

            fromDate = [[inputDate  dateByAddingTimeInterval: frominterval] retain];


            NSLog(@"fromDate------zh---------%@",fromDate);



- (id)initWithFrame:(CGRect)frame {

    if ((self = [super initWithFrame:frame])) {

//默認日期格式爲yyyy-MM-dd

dateFormatter= [[NSDateFormatter alloc] init];

[dateFormatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];//location設置爲中國

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

//picker的默認時間爲當前時間

date=[NSDate date];

//picker的默認style爲只顯示日期

datePickerMode=UIDatePickerModeDate;

//構造一個子視圖,用於顯示日期選擇器

subview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];

subview.backgroundColor=[UIColor clearColor];

subview.tag=0;



*/



說明:上面的時間是美國時間,下面的沒有設置

 

   NSString* string = @"Wed, 05 May 2011 10:50:00 +0800";

    NSDateFormatter *inputFormatter = [[[NSDateFormatter allocinitautorelease];

    [inputFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];

    [inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];

    NSDate* inputDate = [inputFormatter dateFromString:string];

    NSLog(@"date = %@", inputDate);


// 獲得本地時間指定時區
                    NSDate *dates = [NSDate date];
                    NSDateFormatter *formatter =  [[NSDateFormatter alloc] init];
                    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/beijing"];
                    [formatter setTimeZone:timeZone];
                    NSString *loctime = [formatter stringFromDate:dates];



2、以前一直爲這個事情糾結,無奈只能拼接字符串:

 

NSString *str=@"20120403000000";

 

NSString *dateStr=[NSString stringWithFormat:@"有效期至:%@%@%@",

                           [str substringWithRange:NSMakeRange(04)],

                           [str substringWithRange:NSMakeRange(42)],

                           [str substringWithRange:NSMakeRange(62)]];

這個方法笨,可是沒辦法,查了好多資料,都沒明白,今天突然明白了,呵呵,只要把那個[inputFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];@“”裏面的格式轉化爲你字符串的格式一切就OK了,不知道我說明白了嗎

3、iOS-NSDateFormatter 格式說明:

 

G: 公元時代,例如AD公元

    yy: 年的後2位

    yyyy: 完整年

    MM: 月,顯示爲1-12

    MMM: 月,顯示爲英文月份簡寫,如 Jan

    MMMM: 月,顯示爲英文月份全稱,如 Janualy

    dd: 日,2位數表示,如02

    d: 日,1-2位顯示,如 2

    EEE: 簡寫星期幾,如Sun

    EEEE: 全寫星期幾,如Sunday

    aa: 上下午,AM/PM

    H: 時,24小時制,0-23

    K:時,12小時制,0-11

    m: 分,1-2位

    mm: 分,2位

    s: 秒,1-2位

    ss: 秒,2位

    S: 毫秒


常用日期結構:

yyyy-MM-dd HH:mm:ss.SSS

yyyy-MM-dd HH:mm:ss

yyyy-MM-dd

MM dd yyyy




下面得到日期是數字,可以避免語言不同問題

取得當前的年月日,當前的時分秒獲得,周幾和星期幾獲得


NSDate*date = [NSDate date];

NSCalendar*calendar = [NSCalendar currentCalendar];

NSDateComponents*comps;

 

// 年月日獲得

comps =[calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |NSDayCalendarUnit)

                                      fromDate:date];

NSIntegeryear = [comps year];

NSIntegermonth = [comps month];

NSIntegerday = [comps day];

NSLog(@"year:%d month: %d, day: %d", year, month, day);

 

//當前的時分秒獲得

comps =[calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit |NSSecondCalendarUnit)

                                      fromDate:date];

NSIntegerhour = [comps hour];

NSIntegerminute = [comps minute];

NSIntegersecond = [comps second];

NSLog(@"hour:%d minute: %d second: %d", hour, minute, second);

 

// 周幾和星期幾獲得

comps =[calendar components:(NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit)

                                      fromDate:date];

NSInteger week = [comps week]; // 今年的第幾周

NSIntegerweekday = [comps weekday]; // 星期幾(注意,週日是“1”,週一是“2”。。。。)

NSIntegerweekdayOrdinal = [comps weekdayOrdinal]; // 這個月的第幾周

NSLog(@"week:%d weekday: %d weekday ordinal: %d", week, weekday, weekdayOrdinal);

 

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

       if(dateSwitch.on)

       [dateFormattersetDateFormat:@"dd-MMM-yyy,hh:mm:ss"];

       else

       [dateFormatter setDateFormat:@"hh:mm:ss"];

       labelTime.text = [dateFormatter stringFromDate:[NSDatedate]];

       labelTime.font = [UIFontsystemFontOfSize:fontSlider.value];

       [dateFormatter release];



#pramark -------------------





NSDate存儲的是世界標準時(UTC),輸出時需要根據時區轉換爲本地時間

 

Dates

        NSDate類提供了創建date,比較date以及計算兩個date之間間隔的功能。Date對象是不可改變的。

        如果你要創建date對象並表示當前日期,你可以alloc一個NSDate對象並調用init初始化:

C代碼  收藏代碼
  1. NSDate *now = [[NSDate alloc] init];    
  

          或者使用NSDate的date類方法來創建一個日期對象。如果你需要與當前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更復雜的calendar或date components對象。

 

        創建一定時間間隔的NSDate對象:

C代碼  收藏代碼
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;    
  2.     
  3. NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];    
  4.     
  5. NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];    
  6.     
  7. [tomorrow release];    
  8. [yesterday release];    
  

        使用增加時間間隔的方式來生成NSDate對象:

C代碼  收藏代碼
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;    
  2.     
  3. NSDate *today = [[NSDate alloc] init];    
  4. NSDate *tomorrow, *yesterday;    
  5.     
  6. tomorrow = [today dateByAddingTimeInterval: secondsPerDay];    
  7. yesterday = [today dateByAddingTimeInterval: -secondsPerDay];    
  8.     
  9. [today release];    

 

        如果要對NSDate對象進行比較,可以使用isEqualToDate:, compare:, laterDate:和 earlierDate:方法。這些方法都進行精確比較,也就是說這些方法會一直精確比較到NSDate對象中秒一級。例如,你可能比較兩個日期,如果他們之間的間隔在一分鐘之內則認爲這兩個日期是相等的。在這種情況下使用,timeIntervalSinceDate:方法來對兩個日期進行比較。下面的代碼進行了示例:

C代碼  收藏代碼
  1. if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...   
 

NSCalendar & NSDateComponents

 

        日曆對象封裝了對系統日期的計算,包括這一年開始,總天數以及劃分。你將使用日曆對象對絕對日期與date components(包括年,月,日,時,分,秒)進行轉換。

 

        NSCalendar定義了不同的日曆,包括佛教歷,格里高利曆等(這些都與系統提供的本地化設置相關)。NSCalendar與NSDateComponents對象緊密相關。

 

        你可以通過NSCalendar對象的currentCalendar方法來獲得當前系統用戶設置的日曆。

C代碼  收藏代碼
  1. NSCalendar *currentCalendar = [NSCalendar currentCalendar];    
  2. NSCalendar *japaneseCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];    
  3. NSCalendar *usersCalendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];    
 

        usersCalendar和currentCalendar對象是相等的,儘管他們是不同的對象。

 

        你可以使用NSDateComponents對象來表示一個日期對象的組件——例如年,月,日和小時。如果要使一個NSDateComponents對象有意義,你必須將其與一個日曆對象相關聯。下面的代碼示例瞭如何創建一個NSDateComponents對象:

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setDay:6];    
  4. [components setMonth:5];    
  5. [components setYear:2004];    
  6.     
  7. NSInteger weekday = [components weekday]; // Undefined (== NSUndefinedDateComponent)    
 

        要將一個日期對象解析到相應的date components,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents對象返回組件。

C代碼  收藏代碼
  1. NSDate *today = [NSDate date];    
  2.     
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  4.     
  5. NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];    
  6.     
  7. NSInteger day = [weekdayComponents day];    
  8. NSInteger weekday = [weekdayComponents weekday];  
 

同樣你也可以從NSDateComponents對象來創建NSDate對象:  

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setWeekday:2]; // Monday    
  4. [components setWeekdayOrdinal:1]; // The first Monday in the month    
  5. [components setMonth:5]; // May    
  6. [components setYear:2008];    
  7.     
  8. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  9.     
  10. NSDate *date = [gregorian dateFromComponents:components];    
 

        爲了保證正確的行爲,您必須確保使用的組件在日曆上是有意義的。指定“出界”日曆組件,如一個-6或2月30日在公曆中的日期值產生未定義的行爲。

 

        你也可以創建一個不帶年份的NSDate對象,這樣的操作系統會自動生成一個年份,但在後面的代碼中不會使用其自動生成的年份。

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setMonth:11];    
  4. [components setDay:7];    
  5.     
  6. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  7.     
  8. NSDate *birthday = [gregorian dateFromComponents:components];   
 

下面的示例顯示瞭如何從一個日曆置換到另一個日曆:

C代碼  收藏代碼
  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    
 

曆法計算

 

    在當前時間加上一個半小時:

C代碼  收藏代碼
  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];    
 

    獲得當前星期中的星期天(使用格里高利曆):

C代碼  收藏代碼
  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];    
 

    如何可以計算出一週的第一天(根據系統的日曆設置):

C代碼  收藏代碼
  1. NSDate *today = [[NSDate alloc] init];    
  2.     
  3. NSDate *beginningOfWeek = nil;    
  4.     
  5. BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];    
 

    獲得兩個日期之間的間隔:

C代碼  收藏代碼
  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來計算同一時代(AD|BC)兩個日期午夜之間的天數:

C代碼  收藏代碼
  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來計算不同時代(AD|BC)兩個日期的天數:

C代碼  收藏代碼
  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   

 

    判斷一個日期是否在當前一週內(使用格里高利曆):

C代碼  收藏代碼
  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. }    
 

 

來源:http://blog.csdn.net/lingedeng/article/details/6996599

 

 

 

1、獲取當前時間

 

C代碼  收藏代碼
  1. NSDateFormatter*formatter = [[NSDateFormatteralloc] init];  
  2. [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  
  3. NSString *locationString=[formatter stringFromDate: [NSDate date]];  
 

另外的方法:

 

C代碼  收藏代碼
  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日期格式將默認爲24小時制,小寫的h日期格式將默認爲12小時

//不需要特別設置,只需要在dataFormat裏設置類似"yyyy-MMM-dd"這樣的格式就可以了

 

日期格式如下:

y  年  Year  1996; 96  

M  年中的月份  Month  July; Jul; 07  

w  年中的週數  Number  27  

W  月份中的週數  Number  2  

D  年中的天數  Number  189  

d  月份中的天數  Number  10  

F  月份中的星期  Number  2  

E  星期中的天數  Text  Tuesday; Tue  

a  Am/pm 標記  Text  PM  

H  一天中的小時數(0-23)  Number  0  

k  一天中的小時數(1-24)  Number  24  

K  am/pm 中的小時數(0-11)  Number  0  

h  am/pm 中的小時數(1-12)  Number  12  

m  小時中的分鐘數  Number  30  

s  分鐘中的秒數  Number  55  

S  毫秒數  Number  978  

z  時區  General time zone  Pacific Standard Time; PST; GMT-08:00  

Z  時區  RFC 822 time zone  -0800

 

2、NSTimer定時器的基本操作方式

NSTimer是Cocoa中比較常用的定時器類,基本操作如下:

handleTimer方法可以自行定義。在需要的地方創建timer即可,handleTimer就可以每0.5秒執行一次。

 

C代碼  收藏代碼
  1.  - (void) handleTimer: (NSTimer *) timer  
  2. {  
  3.    //在這裏進行處理  
  4. }   
  5. NSTimer *timer;  
  6. timer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(handleTimer:)userInfo: nil repeats: YES];  
 

3、定時器

設置定時器下面顯示的定時器將在一秒鐘後觸發,並一直重複直到定時器被禁用。定時器每次激活時,就會調用發送選擇器消息的目標來進行初始化。回調方法帶有一個參數,就是定時器本身.要禁用一個定時器,給它發送invalidate消息,這將釋放定時器對象並把它從當前運行循環中刪除。

C代碼  收藏代碼
  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. }  

 

來源: http://blog.csdn.net/imekong/article/details/7041312

 

 

1. 使用 NSTimeZone 取得世界各地時間的方法

 下列程式碼將示範,如何利用 NSTimeZone 取得世界上已知的時區名稱,並且透過這些名稱來獲得當地時間,如果在系統時間的取得上有任何疑問,可以參考取得 iOS 系統日期與星期的方法一文,其程式碼如下。

C代碼  收藏代碼
  1. //取得目前已知的所有地裏名稱  
  2. NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];   
  3.   
  4. //取得本地目前時間  
  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. //設定時間格式  
  12. [formatter setDateFormat:@"YYYY-MM-d HH:mm:ss"];   
  13.   
  14. //設定時區  
  15. [formatter setTimeZone:timezone];   
  16.   
  17. //時間格式正規化並做時區校正  
  18. NSString *correctDate = [formatter stringFromDate:date];  
  19.   
  20. NSLog(@"地點:%@ 當地時間:%@",[timezone name], correctDate);   
  21.   
  22. [formatter release];   
  23. [timezone release];   
  24. }  
 

NSDate存儲的是世界標準時(UTC),輸出時需要根據時區轉換爲本地時間

 

Dates

        NSDate類提供了創建date,比較date以及計算兩個date之間間隔的功能。Date對象是不可改變的。

        如果你要創建date對象並表示當前日期,你可以alloc一個NSDate對象並調用init初始化:

C代碼  收藏代碼
  1. NSDate *now = [[NSDate alloc] init];    
  

          或者使用NSDate的date類方法來創建一個日期對象。如果你需要與當前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更復雜的calendar或date components對象。

 

        創建一定時間間隔的NSDate對象:

C代碼  收藏代碼
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;    
  2.     
  3. NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];    
  4.     
  5. NSDate *yesterday = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];    
  6.     
  7. [tomorrow release];    
  8. [yesterday release];    
  

        使用增加時間間隔的方式來生成NSDate對象:

C代碼  收藏代碼
  1. NSTimeInterval secondsPerDay = 24 * 60 * 60;    
  2.     
  3. NSDate *today = [[NSDate alloc] init];    
  4. NSDate *tomorrow, *yesterday;    
  5.     
  6. tomorrow = [today dateByAddingTimeInterval: secondsPerDay];    
  7. yesterday = [today dateByAddingTimeInterval: -secondsPerDay];    
  8.     
  9. [today release];    

 

        如果要對NSDate對象進行比較,可以使用isEqualToDate:, compare:, laterDate:和 earlierDate:方法。這些方法都進行精確比較,也就是說這些方法會一直精確比較到NSDate對象中秒一級。例如,你可能比較兩個日期,如果他們之間的間隔在一分鐘之內則認爲這兩個日期是相等的。在這種情況下使用,timeIntervalSinceDate:方法來對兩個日期進行比較。下面的代碼進行了示例:

C代碼  收藏代碼
  1. if (fabs([date2 timeIntervalSinceDate:date1]) < 60) ...   
 

NSCalendar & NSDateComponents

 

        日曆對象封裝了對系統日期的計算,包括這一年開始,總天數以及劃分。你將使用日曆對象對絕對日期與date components(包括年,月,日,時,分,秒)進行轉換。

 

        NSCalendar定義了不同的日曆,包括佛教歷,格里高利曆等(這些都與系統提供的本地化設置相關)。NSCalendar與NSDateComponents對象緊密相關。

 

        你可以通過NSCalendar對象的currentCalendar方法來獲得當前系統用戶設置的日曆。

C代碼  收藏代碼
  1. NSCalendar *currentCalendar = [NSCalendar currentCalendar];    
  2. NSCalendar *japaneseCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSJapaneseCalendar];    
  3. NSCalendar *usersCalendar = [[NSLocale currentLocale] objectForKey:NSLocaleCalendar];    
 

        usersCalendar和currentCalendar對象是相等的,儘管他們是不同的對象。

 

        你可以使用NSDateComponents對象來表示一個日期對象的組件——例如年,月,日和小時。如果要使一個NSDateComponents對象有意義,你必須將其與一個日曆對象相關聯。下面的代碼示例瞭如何創建一個NSDateComponents對象:

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setDay:6];    
  4. [components setMonth:5];    
  5. [components setYear:2004];    
  6.     
  7. NSInteger weekday = [components weekday]; // Undefined (== NSUndefinedDateComponent)    
 

        要將一個日期對象解析到相應的date components,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents對象返回組件。

C代碼  收藏代碼
  1. NSDate *today = [NSDate date];    
  2.     
  3. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  4.     
  5. NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];    
  6.     
  7. NSInteger day = [weekdayComponents day];    
  8. NSInteger weekday = [weekdayComponents weekday];  
 

同樣你也可以從NSDateComponents對象來創建NSDate對象:  

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setWeekday:2]; // Monday    
  4. [components setWeekdayOrdinal:1]; // The first Monday in the month    
  5. [components setMonth:5]; // May    
  6. [components setYear:2008];    
  7.     
  8. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  9.     
  10. NSDate *date = [gregorian dateFromComponents:components];    
 

        爲了保證正確的行爲,您必須確保使用的組件在日曆上是有意義的。指定“出界”日曆組件,如一個-6或2月30日在公曆中的日期值產生未定義的行爲。

 

        你也可以創建一個不帶年份的NSDate對象,這樣的操作系統會自動生成一個年份,但在後面的代碼中不會使用其自動生成的年份。

C代碼  收藏代碼
  1. NSDateComponents *components = [[NSDateComponents alloc] init];    
  2.     
  3. [components setMonth:11];    
  4. [components setDay:7];    
  5.     
  6. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];    
  7.     
  8. NSDate *birthday = [gregorian dateFromComponents:components];   
 

下面的示例顯示瞭如何從一個日曆置換到另一個日曆:

C代碼  收藏代碼
  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    
 

曆法計算

 

    在當前時間加上一個半小時:

C代碼  收藏代碼
  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];    
 

    獲得當前星期中的星期天(使用格里高利曆):

C代碼  收藏代碼
  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];    
 

    如何可以計算出一週的第一天(根據系統的日曆設置):

C代碼  收藏代碼
  1. NSDate *today = [[NSDate alloc] init];    
  2.     
  3. NSDate *beginningOfWeek = nil;    
  4.     
  5. BOOL ok = [gregorian rangeOfUnit:NSWeekCalendarUnit startDate:&beginningOfWeek interval:NULL forDate: today];    
 

    獲得兩個日期之間的間隔:

C代碼  收藏代碼
  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來計算同一時代(AD|BC)兩個日期午夜之間的天數:

C代碼  收藏代碼
  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來計算不同時代(AD|BC)兩個日期的天數:

C代碼  收藏代碼
  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   

 

    判斷一個日期是否在當前一週內(使用格里高利曆):

C代碼  收藏代碼
  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. }    
 

 

來源:http://blog.csdn.net/lingedeng/article/details/6996599

 

 

 

1、獲取當前時間

 

C代碼  收藏代碼
  1. NSDateFormatter*formatter = [[NSDateFormatteralloc] init];  
  2. [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];  
  3. NSString *locationString=[formatter stringFromDate: [NSDate date]];  
 

另外的方法:

 

C代碼  收藏代碼
  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日期格式將默認爲24小時制,小寫的h日期格式將默認爲12小時

//不需要特別設置,只需要在dataFormat裏設置類似"yyyy-MMM-dd"這樣的格式就可以了

 

日期格式如下:

y  年  Year  1996; 96  

M  年中的月份  Month  July; Jul; 07  

w  年中的週數  Number  27  

W  月份中的週數  Number  2  

D  年中的天數  Number  189  

d  月份中的天數  Number  10  

F  月份中的星期  Number  2  

E  星期中的天數  Text  Tuesday; Tue  

a  Am/pm 標記  Text  PM  

H  一天中的小時數(0-23)  Number  0  

k  一天中的小時數(1-24)  Number  24  

K  am/pm 中的小時數(0-11)  Number  0  

h  am/pm 中的小時數(1-12)  Number  12  

m  小時中的分鐘數  Number  30  

s  分鐘中的秒數  Number  55  

S  毫秒數  Number  978  

z  時區  General time zone  Pacific Standard Time; PST; GMT-08:00  

Z  時區  RFC 822 time zone  -0800

 

2、NSTimer定時器的基本操作方式

NSTimer是Cocoa中比較常用的定時器類,基本操作如下:

handleTimer方法可以自行定義。在需要的地方創建timer即可,handleTimer就可以每0.5秒執行一次。

 

C代碼  收藏代碼
  1.  - (void) handleTimer: (NSTimer *) timer  
  2. {  
  3.    //在這裏進行處理  
  4. }   
  5. NSTimer *timer;  
  6. timer = [NSTimer scheduledTimerWithTimeInterval: 0.5 target: self selector: @selector(handleTimer:)userInfo: nil repeats: YES];  
 

3、定時器

設置定時器下面顯示的定時器將在一秒鐘後觸發,並一直重複直到定時器被禁用。定時器每次激活時,就會調用發送選擇器消息的目標來進行初始化。回調方法帶有一個參數,就是定時器本身.要禁用一個定時器,給它發送invalidate消息,這將釋放定時器對象並把它從當前運行循環中刪除。

C代碼  收藏代碼
  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. }  

 

來源: http://blog.csdn.net/imekong/article/details/7041312

 

 

1. 使用 NSTimeZone 取得世界各地時間的方法

 下列程式碼將示範,如何利用 NSTimeZone 取得世界上已知的時區名稱,並且透過這些名稱來獲得當地時間,如果在系統時間的取得上有任何疑問,可以參考取得 iOS 系統日期與星期的方法一文,其程式碼如下。

C代碼  收藏代碼
  1. //取得目前已知的所有地裏名稱  
  2. NSArray *timeZoneNames = [NSTimeZone knownTimeZoneNames];   
  3.   
  4. //取得本地目前時間  
  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. //設定時間格式  
  12. [formatter setDateFormat:@"YYYY-MM-d HH:mm:ss"];   
  13.   
  14. //設定時區  
  15. [formatter setTimeZone:timezone];   
  16.   
  17. //時間格式正規化並做時區校正  
  18. NSString *correctDate = [formatter stringFromDate:date];  
  19.   
  20. NSLog(@"地點:%@ 當地時間:%@",[timezone name], correctDate);   
  21.   
  22. [formatter release];   
  23. [timezone release];   
  24. }  
發佈了35 篇原創文章 · 獲贊 0 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章