前几天做一个需求就是,通过判断用户进入界面的时间,来决定给用户推送不同的内容,这里面需要注意两个类 NSCalendar和NSDateComponents两个类
//1. 建立一个遵循某个历法的日历 NSCalendar *greCalender = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar]; //2. 通过日历对象获取时间点信息 NSDateComponents *dataCompontents = [greCalender components:NSUIntegerMax fromDate:[NSDate date]]; NSLog(@"现在是北京时间:%ld点",(long)dataCompontents.hour); // 3.比较判断(2--14点规定为上午) if(dataCompontents.hour>2&&dataCompontents.hour<=14){ NSLog(@"上午"); }else{ NSLog(@"下午"); }
2.谈谈iOS中时间处理的一般做法:NSCalendar && NSDateComponents,下面是apple给出的例子,关于这个我看到了一篇写的不错的文章http://my.oschina.net/yongbin45/blog/156181,讲的比较详细,可以参考看看
NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:6]; [comps setMonth:5]; [comps setYear:2004]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *date = [gregorian dateFromComponents:comps]; [comps release]; NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:date]; int weekday = [weekdayComponents weekday];
原文:http://my.oschina.net/shoutan/blog/513695