写了篇关于NSDate和NSCalendar的文章,本想发到博客园的,结果网站有问题,就到这来凑热闹了,希望朋友们多多提意见。。
日历对象封装了对系统日期的计算,包括这一年的开始,总天数以及划分。我们将使用日历对象对绝对日期与components(包括年、月、日、时、分、秒)进行转换。
1. 在开始之前,我们应该告知系统我们当前的时间和日期。NSDate是取当前时间和日期的方法。
NSDate * date = [NSDate date];//定义当前系统时间
2. currentCalendar来获得当前系统用户设置的日历对象。
NSCalendar * currentCalendar = [NSCalendar currentCalendar];//设置当前的日历对象
3. 要从里面取值,还得定义其它的组件:NSComponents来表示一个日期对象的组件---例如年、月、日和小时。
NSDateComponents * components = [[NSDateComponents alloc]init];//定义里面的组件
4. 如果要使NSDateComponents对象有意义,必须将其与一个日历对象相关联。
NSDatecomponents * dateComponents = [currentCalents components: NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit| NSHourCalendarUnit| NSMinuteCalendarUnit| NSSecondCalendarUnit| NSWeekCalendarUnit| NSWeekOfMonthCalendarUnit fromDate:date];//告知日历里面的组件究竟有哪些
5. 前面已经定义好了,下面就可以依次取里面的值了。
NSLog(@“year:%ld”,[dateComponents year]);//调用里面的年份的值
其他的也可以类似一一调用了。
上面是从日历里面输出组件的值,下面我们可以正好反过来,先定义组件,然后给组件进行赋值,最后输出的日历里面仅有我们定义的几个组件。
1. 先定义一个组件:
NSDateComponents * components = [[[NSDateComponents alloc]init]autorelease];//定义组件,并且自动释放
2. 对里面的组件进行赋值:
[components setYear:2013];
[components setMonth:4];
[components setDay:25];
[components setHour:16];
3. 定义一个日历对象:
NSCalendar *current = [[NSCalendar currentCalendar];
4. 定义一个日期对象,显示含有所定义组件的日期:
NSDate * date = [current dateFromComponents :compoments];
5. 输出这个日历:
NSLog(@”date:%@”,date);
今天老师讲的时候,觉得乱起八糟的,现在整理整理,发现还是那么简单。下回争取在老师讲之前就弄懂。。。下面的一篇要介绍NSDateFormater。