(固定格式)
创建:NSDate *date = [NSdate date];
格式化:NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
设置格式:formatter.dateFormat = @“yyyy-MM-dd HH:mm:ss”;
转换:NSString *time = [ formatter stringFormDate:date ];
// NSDate
// 1.NSDate转换NSString
// 创建
NSDate *date = [NSDate date];
// 格式化方法声明
NSDateFormatter *sdf = [[NSDateFormatter alloc] init];
// 设置是时间格式
sdf.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 转换
NSString *time = [sdf stringFromDate:date];
// 输出
NSLog(@"日期:---> %@",time);
// 2.NSString转NSDate
//设置字符串
NSString *str = @"2020-12-12 12:12:12";
//格式化
NSDateFormatter *ndf = [[NSDateFormatter alloc] init];
// 设置格式
ndf.dateFormat = @"yyyy-MM-dd HH-mm-ss";
// 转换
NSDate *d = [ndf dateFromString:str];
// 输出
NSLog(@"%@",d);
// 3.NSCalendar
// 创建
NSCalendar *dar = [NSCalendar currentCalendar];
// 位枚举 声明获取的位置
NSCalendarUnit unit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
// 获取
NSDateComponents *cmp = [dar components:unit fromDate:date];
// 显示
NSLog(@"%ld%ld%ld",cmp.year,cmp.month,cmp.day);
//-------------------------- 计算两个日期之间的差 --------------------------
NSString *time1 = @"2012-12-12 12:00:00";
NSString *time2 = @"2013-12-12 12:00:00";
// 格式化函数
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//设置格式
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 将NSString转换成NSDate
NSData *dat1 = [formatter dateFromString:time1];
NSData *dat2 = [formatter dateFromString:time2];
// 声明NSCalendar
NSCalendar *calender = [NSCalendar currentCalendar];
// 位枚举
NSCalendarUnit unit = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
// 开始比较
NSDateComponents *com = [calender components:unit fromDate:dat1 toDate:dat2 options:0];
// 显示
NSLog(@"日期相差:%ld年:%ld月:%ld日 时:%ld份:%ld :秒",com.year,com.month,com.day,com.hour,com.minute,com.second);