时间&日期 NSDate、NSDateFormatter、NSCalendar

一、获取当前时间

1
2
3
4
5
6
7
8
//获取当前时间
- (NSString *)currentDateStr{
NSDate *currentDate = [NSDate date];//获取当前时间,日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
[dateFormatter setDateFormat:@"YYYY/MM/dd hh:mm:ss SS "];//设定时间格式,这里可以设置成自己需要的格式
NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
return dateString;
}

二、获取当前时间戳

1
2
3
4
5
6
7
//获取当前时间戳
- (NSString *)currentTimeStr{
NSDate* date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
NSTimeInterval time=[date timeIntervalSince1970]*1000;// *1000 是精确到毫秒,不乘就是精确到秒
NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
return timeString;
}

三、时间戳转时间

1
2
3
4
5
6
7
8
9
10
// 时间戳转时间,时间戳为13位是精确到毫秒的,10位精确到秒
- (NSString *)getDateStringWithTimeStr:(NSString *)str{
NSTimeInterval time=[str doubleValue]/1000;//传入的时间戳str如果是精确到毫秒的记得要/1000
NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:time];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //实例化一个NSDateFormatter对象
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss SS"];
NSString *currentDateStr = [dateFormatter stringFromDate: detailDate];
return currentDateStr;
}

四、字符串转时间戳

1
2
3
4
5
6
7
8
//字符串转时间戳 如:2017-4-10 17:15:10
- (NSString *)getTimeStrWithString:(NSString *)str{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; //设定时间的格式
NSDate *tempDate = [dateFormatter dateFromString:str];//将字符串转换为时间对象
NSString *timeStr = [NSString stringWithFormat:@"%ld", (long)[tempDate timeIntervalSince1970]*1000];//字符串转成时间戳,精确到毫秒*1000
return timeStr;
}

五、获取NSDate的年月日

1.NSDateFormat获取
1
2
3
4
5
6
7
8
9
10
11
NSDate *date =[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];

[formatter setDateFormat:@"yyyy"];
NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
[formatter setDateFormat:@"MM"];
NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
[formatter setDateFormat:@"dd"];
NSInteger currentDay=[[formatter stringFromDate:date] integerValue];

NSLog(@"currentDate = %@ ,year = %ld ,month=%ld, day=%ld",date,currentYear,currentMonth,currentDay);
2.NSDateComponents获取
1
2
3
4
5
6
7
8
NSDate  *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];

NSInteger year=[components year];
NSInteger month=[components month];
NSInteger day=[components day];
NSLog(@"currentDate = %@ ,year = %ld ,month=%ld, day=%ld",currentDate,year,month,day);