美文网首页
IOS_计算当前时间与某时间的时间差

IOS_计算当前时间与某时间的时间差

作者: 夏天爱西瓜汁 | 来源:发表于2017-11-28 11:22 被阅读13次

2016.8.12

相差天数:

- (int)intervalSinceNow: (NSString *) theDate

{

NSDateFormatter *date=[[NSDateFormatter alloc] init];

[date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *d=[date dateFromString:theDate];

NSTimeInterval late=[d timeIntervalSince1970]*1;

NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];

NSTimeInterval now=[dat timeIntervalSince1970]*1;

NSString *timeString=@"";

NSTimeInterval cha=now-late;

if (cha/86400>1)

{

timeString = [NSString stringWithFormat:@"%f", cha/86400];

timeString = [timeString substringToIndex:timeString.length-7];

return [timeString intValue];

}

return -1;

}

相差分钟数:

cha/3600<1   分钟

if (cha/3600>1&&cha/86400<1) 小时

01// 获取当前日期

02NSDate *date = [NSDate date];

03

04// 打印结果: 当前时间 date = 2013-08-16 09:00:04 +0000

05NSLog(@"当前时间 date = %@",date);

06

07// 获取从某个日期开始往前或者往后多久的日期,此处60代表60秒,如果需要获取之前的,将60改为-60即可

08date = [[NSDate alloc] initWithTimeInterval:60 sinceDate:[NSDate date]];

09

10//打印结果:当前时间 往后60s的时间date = 2013-08-16 09:01:04 +0000

11NSLog(@"当前时间 往后60s的时间date = %@",date);

PS:测试时时间是下午5点,但是得到的当前时间却是上午9点,相差了8小时,是时区的问题

解决办法:

1NSTimeZone *zone = [NSTimeZone systemTimeZone];

2

3NSInteger interval = [zone secondsFromGMTForDate: date];

4

5NSDate *localDate = [date  dateByAddingTimeInterval: interval];

6

7// 打印结果 正确当前时间 localDate = 2013-08-16 17:01:04 +0000

8NSLog(@"正确当前时间 localDate = %@",localDate);

相关文章

网友评论

      本文标题:IOS_计算当前时间与某时间的时间差

      本文链接:https://www.haomeiwen.com/subject/skbdbxtx.html