1.先在類目裏定義這倆個變量 { NSDateFormatter *_dataFormater; NSDate *_date; } 2.在viewDidLoad裏面寫這段代碼 _dataFormater = [[NSDateFormatter alloc] init]; [_dataFormater setDateFormat:@"HH:mm:ss"]; [_dataFormater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; //時間格式設置完成 // test curent time // NSTimeInterval timer = [NSDate dateWithTimeIntervalSince1970:]; // NSTimeInterval timer = [[NSDate date] timeIntervalSinceReferenceDate]; //直接從date獲得時間格式 與實際時間相差8小時 NSString *stringFromNowDate = [_dataFormater stringFromDate:[NSDate date]]; NSLog(@"stringFromNowDate : %@", stringFromNowDate); // 輸出: 15:29:37 顯示時間: 23:29 差8小時 // solve workable solution _date = [NSDate date]; NSLog(@"date :%@", _date); NSTimeZone *timeZone = [NSTimeZone systemTimeZone]; NSInteger intetval = [timeZone secondsFromGMTForDate:_date]; NSLog(@"intetval :%d", intetval);// 28800 //如今時間 NSDate *localDate = [_date dateByAddingTimeInterval:intetval]; NSLog(@"localDate :%@", localDate); NSString *stringFromLocal = [_dataFormater stringFromDate:localDate]; NSLog(@"stringFromLocal : %@", stringFromLocal); NSDate *date1 = [_dataFormater dateFromString:@"23:47:10"]; NSLog(@"date1: %@", date1); // nsdate是一個對象類型,日期時間格式很完整的,只是用於程序處理數據或者顯示時不方便,由於通常ios處理的數據對象都是NSString,NSArray,NSDictionary。最好的辦法把nsdate這種日期對象轉化成其中的一種,蘋果開發者文檔提供了轉化格式類NSDateFormatter專門進行NSString和NSDate的互相轉化, // NSTimeInterval是一個簡單數據類型 的重命名 double醒數據 用戶NSDate使用 表示距離某個日期多少秒 或者某個日期距離什麼時間點多少秒 時間戳就是指這個數據。通常是距離1970年的時間距離。有多是毫秒有多是秒,這個要看具體服務器返回,這個詩句返回的是秒 3.在一個button點擊事件裏寫這段代碼: NSTimeZone *zone = [NSTimeZone systemTimeZone]; NSInteger interval = [zone secondsFromGMTForDate:[NSDate date]]; NSDate *localDate = [NSDate dateWithTimeInterval:interval sinceDate:[NSDate date]]; NSLog(@"clicled localDate :%@\nlocalDate.description:%@", localDate, localDate.description); NSString *string = [_dataFormater stringFromDate:localDate]; NSLog(@"%@", string); //假如這是倆個時間時間差 NSTimeInterval interval1 = 28800; NSTimeInterval interval2 = [[NSDate date] timeIntervalSinceDate:_date]; NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:interval1]; NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:interval2]; NSLog(@"date1 :%@", date1); NSLog(@"data2 : %@", date2); NSString *intervalTime1 = [_dataFormater stringFromDate:date1]; NSString *intervalTime2 = [_dataFormater stringFromDate:date2]; NSLog(@"interval1 : %@", intervalTime1); NSLog(@"interval2 : %@", intervalTime2);
不許確確的歡迎指正。ios