1.NSString 转 NSDate格式:
- (NSDate *)stringToDate:(NSSTring *)str {
NSDateFormatter *dateFormatter = [NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM"];//自己改变日期格式
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决八小时时差的问题
NSDate *myDate = [dateFormatter dateFromString:str];
return myDate;
}
2.NSDate 转 NSString格式:
- (NSString *)dateToString:(NSDate *)dateTime {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM"];//自己改变日期格式
NSString *strDate = [dateFormatter stringFromDate:dateTime];
return strDate;
}
3.两个相同的时间日期格式相减:
- (double)dateSecondDifference:(NSString *)startTime endTime:(NSString *)endTime {
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyyMMddHHmmss"];
NSDate *startD =[date dateFromString:startTime];
NSDate *endD = [date dateFromString:endTime];
NSTimeInterval start = [startD timeIntervalSince1970]*1;
NSTimeInterval end = [endD timeIntervalSince1970]*1;
NSTimeInterval value = end - start;
float timeF = (float)value;
return timeF;
}
4.一个是日期格式,获取多少秒之后的日期写法:
- (NSString *)dateAddTime:(NSString *)startTime endTime:(NSString *)endTime {
NSDateFormatter *date = [[NSDateFormatter alloc]init];
[date setDateFormat:@"yyyyMMddHHmmss"];
NSDate *startD =[date dateFromString:startTime];
NSDate *endD = [date dateFromString:endTime];
NSTimeInterval start = [startD timeIntervalSince1970]*1;
NSTimeInterval end = [endD timeIntervalSince1970]*1;
NSTimeInterval value = start + end;
NSString *timDD = [self timeDateFormatted:value];
return timDD;
}
- (NSString *)timeDateFormatted:(NSInteger)totalSeconds
{
NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:totalSeconds];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyyMMddHHmmss";
return [dateFormatter stringFromDate:date];
}
5.日期格式返回时分秒:
-(NSString *)getSSFromSS:(NSString *)totalTime{
NSInteger seconds = [totalTime integerValue];
//format of minute
NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
//format of second
NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
//format of time
NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
return format_time;
}
6.获取当前时间字符串格式:
- (NSString *)getGpsCurrentTime:(NSDate *)date {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyyMMddHHmmss"];
NSString *dateTime = [formatter stringFromDate:date];
return dateTime;
}
7.获取当前时间date格式,转8小时制:
- (NSDate *)getCurrenDate {
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
return localeDate;
}