NSDate常用
标签(空格分隔): 实用编程习惯-coding
[TOC]
1、字符串与日期的相互转换
//NSDate求日期
NSDate *date = [NSDate date];
NSDateFormatter *fm = [[NSDateFormatter alloc] init];
fm.dateFormat = @"yyyy-MM-dd HH-mm-ss";
//-----日期转换成字符串------
NSDate *lastDate = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];
NSString *dateString = [fm stringFromDate:lastDate];
NSLog(@"一天前的日期string :%@",dateString);
//-----字符串转换成日期------
NSString *oneDateString = @"2022-12-6 18:01:33";
fm.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
NSDate *oneDate = [fm dateFromString:oneDateString];
NSLog(@"未来某天的日期Obj :%@",oneDate);
2、NSDateComponents获取日期
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
//日历集合的结构体
NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *comp = [calendar components:units fromDate:date];
NSLog(@"%@",comp);
NSLog(@"%zd年%zd月%zd日",comp.year,comp.month,comp.day);
3 获取前一天或者后一天的日期
最low的方式
- 使用NSDateFormatter减去日期对应的秒数,不过这样,日期天数很多的时候,秒数就几千几万了,所以推荐使用日历里面的日期集合
高b格方式
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
//日历集合的结构体
NSCalendarUnit units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:-1];
[components setMonth:-1];
NSDate *lastMonth = [calendar dateByAddingComponents:components toDate:date options:kNilOptions];
components = [calendar components:units fromDate:lastMonth];
NSLog(@"去年的 上一个月 %@",components);