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]

以及

    // 时间1

NSDate *date1 = [NSDate date];

NSTimeZone *zone1 = [NSTimeZone systemTimeZone];

NSInteger interval1 = [zone1 secondsFromGMTForDate:date1];

NSDate *localDate1 = [date1 dateByAddingTimeInterval:interval1];



// 时间2

NSDate *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;

猜你喜欢

转载自www.cnblogs.com/RoysPhoneBlog/p/9321448.html