1.獲取當前時間的年月日時分秒
// 獲取當前時間
NSDate *now = [NSDate date];
NSLog(@"now = %@", now);
// 日歷
NSCalendar *calendar1 = [NSCalendar currentCalendar];
// 利用日歷類從當前時間對象中獲取 年月日時分秒(單獨獲取出來)
// components: 參數的含義是, 問你需要獲取什么?
// 一般情況下如果一個方法接收一個參數, 這個參數是是一個枚舉 , 那么可以通過|符號, 連接多個枚舉值
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar1 components:type fromDate:now];
NSLog(@"year = %ld", cmps.year);
NSLog(@"month = %ld", cmps.month);
NSLog(@"day = %ld", cmps.day);
NSLog(@"hour = %ld", cmps.hour);
NSLog(@"minute = %ld", cmps.minute);
NSLog(@"second = %ld", cmps.second);
2.比較兩個時間之間的差值, 比較相差多少年多少月多少日多少小時多少分鐘多少秒
// 2.1過去的一個時間
NSString *str = @"2015-06-29 07:05:26 +0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss Z";
NSDate *date = [formatter dateFromString:str];
// 2.2當前的時間
NSDate *now = [NSDate date];
NSLog(@"date = %@", date);
NSLog(@"now = %@", now);
// 2.3比較兩個時間
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit type = NSCalendarUnitYear |
NSCalendarUnitMonth |
NSCalendarUnitDay |
NSCalendarUnitHour |
NSCalendarUnitMinute |
NSCalendarUnitSecond;
NSDateComponents *cmps = [calendar components:type fromDate:date toDate:now options:0];
NSLog(@"%ld年%ld月%ld日%ld小時%ld分鐘%ld秒鐘", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。