码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2017-01-03 18:58:43      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:scale   current   时区   情况   pre   blog   今天   com   als   

 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中获取当前时间,设定时间,并算出差值

标签:scale   current   时区   情况   pre   blog   今天   com   als   

原文地址:http://www.cnblogs.com/hjft/p/6245671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!