iOS开发-时间设置NSDate

来源:互联网 发布:王者挂机软件 编辑:程序博客网 时间:2024/05/14 18:22

在很多时候我们需要对程序中的时间或是日期进行获取以及调整。在iOS上,苹果

提供的是NSDate类来进行对时间的获取和操作详细的操作如下:


创建一个对象,赋值为当前日期date 创建的NSDate对象,获得的永远是0时区的时间,china是东八区,需要加上8个小时

NSDate *date = [NSDate date];

NSTimeZone *zone = [NSTimeZone systemTimeZone];//修改时区

NSInteger interval1 = [zone secondsFromGMTForDate: date];//修改时区
NSDate *localDate1 = [date  dateByAddingTimeInterval: interval1];//修改时区
NSLog(@"今天%@", localDate1);

        
创建一个明天此时的日期(时间间隔是以秒为单位的)dateWithTimeIntervalSinceNow:
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:24 * 60 * 60];
NSInteger interval2 = [zone secondsFromGMTForDate: tomorrow];
NSDate *localDate2 = [tomorrow  dateByAddingTimeInterval: interval2];
NSLog(@"明天%@", localDate2);

        
创建一个昨天此时的日期
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-24 * 60 * 60];
NSInteger interval3 = [zone secondsFromGMTForDate: yesterday];
NSDate *localDate3 = [yesterday dateByAddingTimeInterval: interval3];
NSLog(@"昨天%@", localDate3);
0 0
原创粉丝点击