NSDate NSString间的转化和时间差NSDateCo
2017-11-07 本文已影响237人
纯阳子_
🌰:获取现在时间 转换为字符串(NSDate 转为NSString)
-(NSString *)getCurrentTime
{
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
/*设置日期格式*/
formatter.dateFormat = @"yyyyMMddHHmmss";
NSString *nowTime = [formatter stringFromDate:date];
return nowTime;
}
🌰:NSString字符串转化为NSDate
-(NSDate *)getDateWithString:(NSString *) systemTime {
NSString* sysTime = systemTime;
NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
//设置日期格式这里设置为yyyyMMddHH:mm:ss
dateFomatter.dateFormat = @"yyyyMMddHH:mm:ss";
//转化为NSDate
NSDate* nowDate = [dateFomatter dateFromString:sysTime];
return nowDate;
}
🌰: 获取时间差: systemTime - date
参数1: date:时间日期, NSString 类型,例如20161107070707
参数2: dateFormat:日期格式,例如:yyyyMMddHH:mm:ss
参数3: systemTime:日期时间,NSString 类型,例如20171108080808
注意:参数date和systemTime两个日期字符串的格式一定要和dateFormat的格式相对应
-(NSDateComponents *)getDateComponents:(NSString *)date dateFormat:(NSString *)dateFormat severSystemTime:(NSString *)systemTime {
// 此处添加判断防止出现闪退
if (![date isEqual:[NSNull null]]) {
//将参数1日期字符串systemTime转化为NSDate
NSString* sysTime = systemTime;
NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
//设置日期格式为传来的字符串dateFormat
dateFomatter.dateFormat = dateFormat;
NSDate* nowDate = [dateFomatter dateFromString:sysTime];
// 将参数2日期类型字符串date转换为NSDate
NSString *endTime = date;
// 当前时间字符串格式
NSDateFormatter *endDateFomatter = [[NSDateFormatter alloc] init];
//设置日期格式,为传来的参数dateFormat格式
endDateFomatter.dateFormat = dateFormat;
//转化为日期格式
NSDate* endDate = [endDateFomatter dateFromString:endTime];
// 当前日历
NSCalendar *calendar = [NSCalendar currentCalendar];
// 需要对比的时间数据
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
| NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 对比时间差
NSDateComponents *dateCom = [calendar components:unit fromDate: endDate toDate:nowDate options:0];
//打印 如果参数日期格式对不上的话,可能会打印为空
NSLog(@"------->>年:%d,月:%d,日:%d,时:%d,分:%d,",comp.year, comp.month, comp.day, comp.hour,comp.minute);
return dateCom;
}
return nil;
}