objective c NSDate NSDateComponents NSCalendar

想要获取一天的具体小时,分数以及秒数的状况下需要这三个类的对象一起合作。

NSCalendar只用来指定具体使用的日历的类型,包括:Buddhist, Gregorian, Hebrew, Islamic, and Japanese。可以通过NSLocale进行查看系统支持哪一种设定。

NSDateComponents用来代表日期的元素,例如:年月日小时分数秒数等等,

NSDate is an abstract class that provides behavior for creating dates, comparing dates, representing dates, computing intervals, and similar functionality. NSDate presents a programmatic interface through which suitable date objects are requested and returned. Date objects returned from NSDate are lightweight and immutable since they represent an invariant point in time. This class is designed to provide the foundation for arbitrary calendrical representations.

上述说明,不是生命了NSDate的变量,就可以得到hour, minute, second等关于当前时间的参数了,NSDate的对象只是用来进行比较,创建,表示日期的一种抽象的概念。

想要获取精确的hour, minute, second,需要涉及到NSCalendar Units, 包括:NSDayCalendarUnit, NSWeekdayCalendarUnit, NSHourCalendarUnit, NSMinuteCalendarUnit etc.

NSDate *today = [NSDate date]; 生命NSDate对象
NSCalendar *gregorian = [[NSCalendar alloc] 获取当前的日历类型
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = 获取当前日期的对应的CalendarUnit
                    [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:today];
如果想要获取hour, minute, second,在上述NSDayCalendarUnit|之后添加NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
NSInteger day = [weekdayComponents day];
NSInteger weekday = [weekdayComponents weekday];

至此才可以获取到精确的小时分钟和秒数。

posted on 2012-11-24 16:20  全被用了  阅读(179)  评论(0)    收藏  举报