首页 > 代码库 > iOS中获取当前时间,设定时间,并算出差值

iOS中获取当前时间,设定时间,并算出差值

 1 NSDate *date = [NSDate date];//获取当前时间
 2         NSTimeZone *zone = [NSTimeZone systemTimeZone];//修改时区
 3         NSInteger interval1 = [zone secondsFromGMTForDate: date];//修改时区
 4         _localDate1 = [date  dateByAddingTimeInterval: interval1];//修改时区
 5         NSLog(@"~~~~~~~~~~~~~今天%@\n", _localDate1);
 6         
 7         
 8         NSCalendar *calendar = [NSCalendar currentCalendar];
 9         NSDateComponents *comp = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |    NSDayCalendarUnit fromDate:_localDate1];
10 
11         //获取当前年月日
12         NSInteger year = [comp year];
13         NSInteger month = [comp month];
14         NSInteger day = [comp day];
15         
16         NSDateComponents * components = [[NSDateComponents alloc]init];
17 
18         //设定
19         [components setYear:year];
20         [components setMonth:month];
21         [components setDay:day];
22         [components setHour:16];
23         [components setMinute:32];
24         
25         NSCalendar *current = [NSCalendar currentCalendar];
26         
27         NSDate *setDate1 = [current dateFromComponents:components];
28         //默认的时区都是格林尼治0时区,我们在东8区
29         NSTimeZone *zone2 = [NSTimeZone systemTimeZone];//修改时区
30         NSInteger interval2 = [zone2 secondsFromGMTForDate: setDate1];//修改时区
31         _localDate2 = [setDate1  dateByAddingTimeInterval: interval2];//修改时区
32         
33         NSLog(@"-----------%@\n",_localDate2);
34 //_localDate1-_localDate2,得到的结果默认为秒,可以自己换算
35 NSInteger lastTime = [_localDate2 timeIntervalSinceDate:_localDate1]/60;
36     NSLog(@"!!!!!!!!!!!!%ld\n",lastTime);

获取day的时候会多加一天,不知道是什么情况

iOS中获取当前时间,设定时间,并算出差值