Objective-C学习之NSDateComponents

54 篇文章 51 订阅 ¥9.90 ¥99.00

NSDateComponents

       NSDateComponents封装在一个可扩展的,面向对象的方式的日期组件。它是用来弥补时间的日期和时间组件提供一个指定日期:小时,分钟,秒,日,月,年,等等。它也可以用来指定的时间,例如,5小时16分钟。

       一个NSDateComponents对象不需要定义所有组件领域。当一个NSDateComponents的新实例被创建,日期组件被设置为NSUndefinedDateComponent。

       一个NSDateComponents对象本身是毫无意义的;你需要知道它是针对什么日历解释,你需要知道它的值是否是正整数和值是多少。

       NSDateComponents的实例不负责回答关于一个日期以外的信息,它是需要先初始化的。例如,如果你初始化一个对象为2004年5月6日,其星期几NSUndefinedDateComponent,不是星期四。要得到正确的星期几,你必须创建一个NSCalendar日历实例,创建一个NSDate对象并使用dateFromComponents:方法,然后使用components:fromDate:检索平周几

Getting Information About an NSDateComponents Object

获取一个NSDateComponents对象的信息

era 时代
year
month
day
hour
minute
second
week
weekday星期名称
weekdayOrdinal
quarter 季度
Setting Information for an NSDateComponents Object

设置一个NSDateComponents对象的信息

setEra:时代
setYear:
setMonth:
setDay:
setHour:
setMinute:
setSecond:
setWeek:
setWeekday:星期名称
setWeekdayOrdinal:
setQuarter:季度

       例子如下:获得2004年5月6日是星期几

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];

NSLog(@"%d",weekday);

//一段例子:计算距离某一天还有多少时间
NSDate* toDate   = [ [ NSDate alloc] initWithString:@"2012-9-29 0:0:00 +0600" ]; 

NSDate*  startDate  = [ [ NSDate alloc] init ]; 

NSCalendar* chineseClendar = [ [ NSCalendar alloc ] initWithCalendarIdentifier:NSGregorianCalendar ];  

NSUInteger unitFlags =  
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit;  

NSDateComponents *cps = [chineseClendar components:unitFlags fromDate:startDate  toDate:toDate  options:0];  

NSInteger diffHour = [cps hour];  
NSInteger diffMin  = [cps minute];  
NSInteger diffSec  = [cps second];  
NSInteger diffDay  = [cps day];  
NSInteger diffMon  = [cps month];  
NSInteger diffYear = [cps year];  

NSLog(  @" From Now to %@, diff: Years: %d  Months: %d, Days; %d, Hours: %d, Mins:%d, sec:%d",   

[toDate description], diffYear, diffMon, diffDay, diffHour, diffMin,diffSec );  

[toDate release];  

[startDate release];  

[chineseClendar release];  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值