NSDate NSCalendar NSString之间的故事以及转换
生活随笔
收集整理的這篇文章主要介紹了
NSDate NSCalendar NSString之间的故事以及转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.NSDate 和 NSString 之間的轉換
- 這之間的轉換主要依靠NSDateFormatter
- NSDate <------> NSString
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";NSString *strDate = [formatter stringFrom:date];NSDate *date =[formatter dateFrom:str]; 其中dateFormat格式可以參考蘋果官方文檔Working With Fixed Format Date Representations
2.NSDate通過NSCalendar操作
- 轉化為NSCalendar方便于獲得各種日期參數
-(NSDateComponents*)getDateComponentsFromDate:(NSDate*)date{NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];//設置成中國陽歷NSDateComponents *comps = [[NSDateComponents alloc] init];NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;//這句我也不明白具體時用來做什么。。。comps = [calendar components:unitFlags fromDate:date];return comps;
} - NSDateComponets 可以獲得 年,月,日,以及第幾個星期等等
3. NSDate之間的比較
- 一般用來做文件夾排序等操作
[_dateDirArray sortedArrayUsingComparator: ^NSComparisonResult(__nonnull id obj1,__nonnull id obj2){NSString *stringDateObj1 = obj1;NSString *stringDateObj2 = obj2;NSDate *dateObj1 = [dateFormatter dateFromString:stringDateObj1];NSDate *dateObj2 =[dateFormatter dateFromString:stringDateObj2];return [dateObj1 compare:dateObj2];}] - 另外一種用來計算兩者之間的時間差
//lastDate和nowDate為NSDate類型,最后得到的秒數為lastDate-nowDate所得NSInteger timeDistance= [lastDate timeIntervalSinceDate:nowDate] 以及
// 時間1NSDate *date1 = [NSDate date];NSTimeZone *zone1 = [NSTimeZone systemTimeZone];NSInteger interval1 = [zone1 secondsFromGMTForDate:date1];NSDate *localDate1 = [date1 dateByAddingTimeInterval:interval1];// 時間2NSDate *date2 = [NSDate date];NSTimeZone *zone2 = [NSTimeZone systemTimeZone];NSInteger interval2 = [zone2 secondsFromGMTForDate:date2];NSDate *localDate2 = [date2 dateByAddingTimeInterval:interval2];// 時間2與時間1之間的時間差(秒)double intervalTime = [localDate2 timeIntervalSinceReferenceDate] - [localDate1 timeIntervalSinceReferenceDate];NSInteger seconds = lTime % 60;NSInteger minutes = (lTime / 60) % 60;NSInteger hours = (lTime / 3600);NSInteger days = lTime/60/60/24;NSInteger month = lTime/60/60/24/12;NSInteger years = lTime/60/60/24/365;
轉載于:https://www.cnblogs.com/RoysPhoneBlog/p/9321448.html
總結
以上是生活随笔為你收集整理的NSDate NSCalendar NSString之间的故事以及转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 供暖费的基本费用是多少?
- 下一篇: 求一个带有余生的个性签名!