本文主要是介绍NSDate日期计算,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
时间戳转nsstring
NSTimeInterval interval =[mStr doubleValue] ;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Beijing"]];
NSString *dateString = [formatter stringFromDate: date];
NSDate转string
NSDate *currentDate = [NSDate date];
//用于格式化NSDate对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//设置格式:zzz表示时区
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
//NSDate转NSString
NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
string转NSDate
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];
NSDate *date0 = [formatter dateFromString:str1];
1、计算两个日期的天数差
+(NSInteger)getDaysFrom:(NSDate *)serverDate To:(NSDate *)endDate
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
[gregorian setFirstWeekday:2];
//去掉时分秒信息
NSDate *fromDate;
NSDate *toDate;
[gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:serverDate];
[gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
return dayComponents.day;
}
这篇关于NSDate日期计算的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!