iOS时间转换
2018-06-04 本文已影响37人
Moker_C
记录几种常用的日期格式转化和一些开发中会用到的和日期相关的方法。---“永远不要指望别人把东西给你写全,不然还要你干什么”
转化主要针对以下两个方法:
//date转字符串
- (NSString *)stringFromDate:(NSDate *)date;
//字符串转date
- (nullable NSDate *)dateFromString:(NSString *)string;
1、获取当前时间,并转化成yyyy-MM-dd HH:mm:ss 格式
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//24小时制:yyyy-MM-dd HH:mm:ss 12小时制:yyyy-MM-dd hh:mm:ss
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *nowDateString = [dateFormatter stringFromDate:date];
2、获取当前时间的时间戳
NSDate *date = [NSDate date];
//单位:秒
NSTimeInterval interval = [date timeIntervalSince1970];
3、时间戳转时间字符串
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//24小时制:yyyy-MM-dd HH:mm:ss 12小时制:yyyy-MM-dd hh:mm:ss
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSTimeInterval interval = [@"1528094475" longLongValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSString *dateString = [dateFormatter stringFromDate:date];
4、时间字符串转时间戳
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//24小时制:yyyy-MM-dd HH:mm:ss 12小时制:yyyy-MM-dd hh:mm:ss
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSDate *date = [dateFormatter dateFromString:@"2018-06-04 14:41:15"];
NSTimeInterval interval = [date timeIntervalSince1970];
5、某个时间点与当前时间的间隔(单位:秒)
//时间格式先转换,再比较
NSDate *date = [dateFormatter dateFromString:@"2018-06-04 14:41:15"];
NSTimeInterval interval = [date timeIntervalSince1970];
//如果是时间戳就直接拿时间戳进行下面的转换比较
//NSTimeInterval interval = [@"1528094475" longLongValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSTimeInterval timeInterval = [date timeIntervalSinceNow];//值=某个时间-当前时间
//也可以用下面的方法进行比较(改方法可以比较任意两个时间点的间隔)
//NSDate * currentDate = [NSDate date];
//NSTimeInterval interval = [currentDate timeIntervalSinceDate:date];//值= currentDate-date
6、获取将来的某个时间
NSTimeInterval interval = 24 * 60 * 60;
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:interval];
7、根据某个时间来创建时间
NSTimeInterval interval = 24 * 60 * 60;//正值表示将来,负值表示过去时间
NSDate *date = [NSDate date];
NSDate *tomorrow = [date dateByAddingTimeInterval:interval];
8、日期比较
NSDate * currentDate = [NSDate date];
NSTimeInterval interval = [@"1528094475" longLongValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
//方法一:
//比较时间是否相等
BOOL sameDate = [currentDate isEqualToDate:date];
//获取两个时间中较早的时间
NSDate *earlierDate = [currentDate earlierDate: date];
//获取两个时间中较晚的时间
NSDate *laterDate = [currentDate laterDate: date];
//方法二:
NSComparisonResult result = [currentDate compare:date];
if (result == NSOrderedAscending) {//升序
//currentDate < date
}else if (result == NSOrderedDescending) {//降序
//currentDate > date
}else {//相等
//currentDate == date
}
//方法三:(用日历进行比较)
NSCalendar *calendar = nil;
if ([UIDevice currentDevice].systemVersion.doubleValue >= 8.0) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
// NSCalendar *calendar = nil;
// if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
// calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
// } else {
// calendar = [NSCalendar currentCalendar];
// }
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
// 4.获取了时间元素
NSDateComponents *components = [calendar components:unit fromDate:date toDate: currentDate options:0];
NSLog(@"相差:%ld年%ld月%ld日%ld小时%ld分钟%ld秒钟", (long)components.year, (long)components.month, (long)components.day, (long)components.hour, (long)components.minute, (long)components.second);
下面介绍下NSCalendar的一些用法
1、获取当前时间
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:[NSDate date]];
NSLog(@"%ld-%ld-%ld %ld:%ld:%ld" ,(long)components.year,(long)components.month,(long)components.day,(long)components.hour,(long)components.minute,(long)components.second);
//现在处于今年的几月
NSInteger month = [calendar ordinalityOfUnit:NSCalendarUnitMonth inUnit:NSCalendarUnitYear forDate:[NSDate date]];
NSLog(@"今天是今年的%ld月",(long)month);
//当前日期是今年的第几周
NSInteger week = [calendar ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitYear forDate:[NSDate date]];
NSLog(@"今天是今年的第%ld周",(long)week);
//当前日期是今年的第几天
NSInteger day = [calendar ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitYear forDate:[NSDate date]];
NSLog(@"今天是今年的第%ld天",(long)day);
2、获取过去一周时间
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSMutableArray *dates = [NSMutableArray array];
for (int i=-6; i < 1; i++) {
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = 0;
components.month = 0;
components.day = i;
NSDate *currentDate = [NSDate date];
NSDate *date = [calendar dateByAddingComponents:components toDate:currentDate options:NSCalendarMatchStrictly];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MM-dd";
NSString *dateString = [formatter stringFromDate:date];
[dates addObject:dateString];
}
NSLog(@"%@,%@,%@,%@,%@,%@,%@",dates[0],dates[1],dates[2],dates[3],dates[4],dates[5],dates[6]);
3、获取某个时间点对应的月份有几天
- (NSInteger)getDaysByDate:(NSDate *)date {
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
NSUInteger days = range.length;
return days;
}
4、获取某个时间点对应的月份的某一天的时间
- (NSDate *)getDateByDate:(NSDate *)date day:(int)day {
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *components = [calendar components:unit fromDate:date];
components.day = day;
return [calendar dateFromComponents:components];
}
5、获取某天对应星期几
- (NSInteger)getTheCorrespondingWeekByDate:(NSDate*)date {
NSCalendar *calendar = nil;
if ([NSCalendar respondsToSelector:@selector(calendarWithIdentifier:)]) {
calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
} else {
calendar = [NSCalendar currentCalendar];
}
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
NSInteger weekday = [components weekday];
NSLog(@"weekday = %ld",(long)weekday);
weekday--;//美国从周日开始一周,我们从周一开始,所以我们这得调整
NSLog(@"weekday = %ld",(long)weekday);
if (weekday == 7) {
return 0;
}
return weekday;
}
6、传入时间戳同当前时间比对
- (NSString *)timeAgoWithTimeString:(NSString *)string {
NSDate *date = [NSDate date];
NSTimeInterval timeInterval = [date timeIntervalSince1970];
NSDate *compareDate = [NSDate dateWithTimeIntervalSince1970:[string longLongValue]];
NSTimeInterval compareImterval = [compareDate timeIntervalSince1970];
int difference = timeInterval - compareImterval;
int days = difference/(60*60*24);
int hours = (difference%(60*60*24))/(60*60);
int minites = (difference%(60*60*24))%(60*60)/60;
int seconds = (difference%(60*60*24))%(60*60)%60;
if (days != 0) {
return [NSString stringWithFormat:@"%d天前",days];
}else if (hours != 0) {
return [NSString stringWithFormat:@"%d小时前",hours];
}else if (minites != 0) {
return [NSString stringWithFormat:@"%d分钟前",minites];
}else if (seconds != 0) {
return @"刚刚";
}else {
return @"时间格式有误";
}
}
好了,有这些基本能应对开发过程中对时间的需求了,欢迎舔砖加瓦,朕要休息一会了!!!