使用NSDateFormatter进行NSDate与NSString之间的转化
NSDateFormatter有下面2个方法:
//NSDate转NSString
- (NSString *)stringFromDate:(NSDate *)date;
//NSString转NSDate
- (nullable NSDate *)dateFromString:(NSString *)string;
NSDateFormatter 格式
//EEEE为星期几,EEE为周几
[dateFormatter setDateFormat:@"yyyy年MM月dd日#EEEE"];
//HH为24小时制,hh为12小时制
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//MMMM 为英文月数,一个M可以省去01月前的0,一个d可以省去01日前的0
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
计算两个时间的时间差(xx天xx小时xx分钟的格式)
// 计算两个时间的时间差
NSDateFormatter *date=[[NSDateFormatter alloc] init];
[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSCalendar *cal=[NSCalendar currentCalendar];
unsigned int unitFlags=NSCalendarUnitYear| NSCalendarUnitMonth| NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
NSDateComponents *d = [cal components:unitFlags fromDate:[date dateFromString:@"2014-11-24 17:21:58"] toDate:[date dateFromString:@"2014-12-25 17:22:59"] options:0];
NSLog(@"%ld天%ld小时%ld分钟%ld秒",[d day],[d hour],[d minute],[d second]);
计算两个时间的时间差(秒数)
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *closingDate = [formatter dateFromString:@"2016-09-09 12:00:00"];
NSDate *now = [NSDate date];
CGFloat timeInterval = (CGFloat)[closingDate timeIntervalSinceDate:now];