Dates
NSDate类提供了创建date,比较date以及计算两个date之间间隔的功能。Date对象是不可改变的。
如果你要创建date对象并表示当前日期,你可以alloc一个NSDate对象并调用init初始化:
[cpp]viewplaincopy- NSDate*now=[[NSDatealloc]init];
或者使用NSDate的date类方法来创建一个日期对象。如果你需要与当前日期不同的日期,你可以使用NSDate的initWithTimeInterval...或dateWithTimeInterval...方法,你也可以使用更复杂的calendar或datecomponents对象。
创建一定时间间隔的NSDate对象:
[plain]viewplaincopy- NSTimeIntervalsecondsPerDay=24*60*60;
- NSDate*tomorrow=[[NSDatealloc]initWithTimeIntervalSinceNow:secondsPerDay];
- NSDate*yesterday=[[NSDatealloc]initWithTimeIntervalSinceNow:-secondsPerDay];
- [tomorrowrelease];
- [yesterdayrelease];
使用增加时间间隔的方式来生成NSDate对象:[plain]viewplaincopy
- NSTimeIntervalsecondsPerDay=24*60*60;
- NSDate*today=[[NSDatealloc]init];
- NSDate*tomorrow,*yesterday;
- tomorrow=[todaydateByAddingTimeInterval:secondsPerDay];
- yesterday=[todaydateByAddingTimeInterval:-secondsPerDay];
- [todayrelease];
如果要对NSDate对象进行比较,可以使用isEqualToDate:,compare:, laterDate:和earlierDate:方法。这些方法都进行精确比较,也就是说这些方法会一直精确比较到NSDate对象中秒一级。例如,你可能比较两个日期,如果他们之间的间隔在一分钟之内则认为这两个日期是相等的。在这种情况下使用,timeIntervalSinceDate:方法来对两个日期进行比较。下面的代码进行了示例:[plain]viewplaincopy
- if(fabs([date2timeIntervalSinceDate:date1])<60)...
//数字转换为时间
NSString*time = @"1329038338";
NSDateFormatter*formatter = [[[NSDateFormatter alloc]init]autorelease];[formattersetDateStyle:NSDateFormatterMediumStyle];
[formattersetTimeStyle:NSDateFormatterShortStyle];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
NSDate*confromTimesp = [NSDatedateWithTimeIntervalSince1970:(NSTimeInterval)[timeintValue]];
NSString*confromTimespStr = [formatterstringFromDate:confromTimesp];
timeString = confromTimespStr;
NSCalendar &NSDateComponents
日历对象封装了对系统日期的计算,包括这一年开始,总天数以及划分。你将使用日历对象对绝对日期与datecomponents(包括年,月,日,时,分,秒)进行转换。
NSCalendar定义了不同的日历,包括佛教历,格里高利历等(这些都与系统提供的本地化设置相关)。NSCalendar与NSDateComponents对象紧密相关。
你可以通过NSCalendar对象的currentCalendar方法来获得当前系统用户设置的日历。
[plain]viewplaincopy- NSCalendar*currentCalendar=[NSCalendarcurrentCalendar];
- NSCalendar*japaneseCalendar=[[NSCalendaralloc]initWithCalendarIdentifier:NSJapaneseCalendar];
- NSCalendar*usersCalendar=[[NSLocalecurrentLocale]objectForKey:NSLocaleCalendar];
你可以使用NSDateComponents对象来表示一个日期对象的组件——例如年,月,日和小时。如果要使一个NSDateComponents对象有意义,你必须将其与一个日历对象相关联。下面的代码示例了如何创建一个NSDateComponents对象:
[plain]viewplaincopy- NSDateComponents*components=[[NSDateComponentsalloc]init];
- [componentssetDay:6];
- [componentssetMonth:5];
- [componentssetYear:2004];
- NSIntegerweekday=[componentsweekday];//Undefined(==NSUndefinedDateComponent)
要将一个日期对象解析到相应的datecomponents,你可以使用NSCalendar的components:fromDate:方法。此外日期本身,你需要指定NSDateComponents对象返回组件。[plain]viewplaincopy
- NSDate*today=[NSDatedate];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDateComponents*weekdayComponents=[gregoriancomponents:(NSDayCalendarUnit|NSWeekdayCalendarUnit)fromDate:today];
- NSIntegerday=[weekdayComponentsday];
- NSIntegerweekday=[weekdayComponentsweekday];
- 同样你也可以从NSDateComponents对象来创建NSDate对象:
- NSDateComponents*components=[[NSDateComponentsalloc]init];
- [componentssetWeekday:2];//Monday
- [componentssetWeekdayOrdinal:1];//ThefirstMondayinthemonth
- [componentssetMonth:5];//May
- [componentssetYear:2008];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDate*date=[gregoriandateFromComponents:components];
为了保证正确的行为,您必须确保使用的组件在日历上是有意义的。指定“出界”日历组件,如一个-6或2月30日在公历中的日期值产生未定义的行为。
你也可以创建一个不带年份的NSDate对象,这样的操作系统会自动生成一个年份,但在后面的代码中不会使用其自动生成的年份。
[plain]viewplaincopy- NSDateComponents*components=[[NSDateComponentsalloc]init];
- [componentssetMonth:11];
- [componentssetDay:7];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDate*birthday=[gregoriandateFromComponents:components];
下面的示例显示了如何从一个日历置换到另一个日历:[plain]viewplaincopy
- NSDateComponents*comps=[[NSDateComponentsalloc]init];
- [compssetDay:6];
- [compssetMonth:5];
- [compssetYear:2004];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDate*date=[gregoriandateFromComponents:comps];
- [compsrelease];
- [gregorianrelease];
- NSCalendar*hebrew=[[NSCalendaralloc]initWithCalendarIdentifier:NSHebrewCalendar];
- NSUIntegerunitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
- NSDateComponents*components=[hebrewcomponents:unitFlagsfromDate:date];
- NSIntegerday=[componentsday];//15
- NSIntegermonth=[componentsmonth];//9
- NSIntegeryear=[componentsyear];//5764
历法计算
在当前时间加上一个半小时:
[plain]viewplaincopy- NSDate*today=[[NSDatealloc]init];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSDateComponents*offsetComponents=[[NSDateComponentsalloc]init];
- [offsetComponentssetHour:1];
- [offsetComponentssetMinute:30];
- //Calculatewhen,accordingtoTomLehrer,WorldWarIIIwillend
- NSDate*endOfWorldWar3=[gregoriandateByAddingComponents:offsetComponentstoDate:todayoptions:0];
获得当前星期中的星期天(使用格里高利历):[plain]viewplaincopy
- NSDate*today=[[NSDatealloc]init];
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- //Gettheweekdaycomponentofthecurrentdate
- NSDateComponents*weekdayComponents=[gregoriancomponents:NSWeekdayCalendarUnitfromDate:today];
- NSDateComponents*componentsToSubtract=[[NSDateComponentsalloc]init];
- [componentsToSubtractsetDay:0-([weekdayComponentsweekday]-1)];
- NSDate*beginningOfWeek=[gregoriandateByAddingComponents:componentsToSubtracttoDate:todayoptions:0];
- NSDateComponents*components=[gregoriancomponents:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)fromDate:beginningOfWeek];
- beginningOfWeek=[gregoriandateFromComponents:components];
如何可以计算出一周的第一天(根据系统的日历设置):
[cpp]viewplaincopy- NSDate*today=[[NSDatealloc]init];
- NSDate*beginningOfWeek=nil;
- BOOLok=[gregorianrangeOfUnit:NSWeekCalendarUnitstartDate:&beginningOfWeekinterval:NULLforDate:today];
获得两个日期之间的间隔:[cpp]viewplaincopy
- NSDate*startDate=...;
- NSDate*endDate=...;
- NSCalendar*gregorian=[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];
- NSUIntegerunitFlags=NSMonthCalendarUnit|NSDayCalendarUnit;
- NSDateComponents*components=[gregoriancomponents:unitFlagsfromDate:startDatetoDate:endDateoptions:0];
- NSIntegermonths=[componentsmonth];
- NSIntegerdays=[componentsday];
使用Category来计算同一时代(AD|BC)两个日期午夜之间的天数:
[plain]viewplaincopy- @implementationNSCalendar(MySpecialCalculations)
- -(NSInteger)daysWithinEraFromDate:(NSDate*)startDatetoDate:(NSDate*)endDate{
- NSIntegerstartDay=[selfordinalityOfUnit:NSDayCalendarUnitinUnit:NSEraCalendarUnitforDate:startDate];
- NSIntegerendDay=[selfordinalityOfUnit:NSDayCalendarUnitinUnit:NSEraCalendarUnitforDate:endDate];
- returnendDay-startDay;
- }
- @end
使用Category来计算不同时代(AD|BC)两个日期的天数:[plain]viewplaincopy
- @implementationNSCalendar(MyOtherMethod)
- -(NSInteger)daysFromDate:(NSDate*)startDatetoDate:(NSDate*)endDate{
- NSCalendarUnitunits=NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
- NSDateComponents*comp1=[selfcomponents:unitsfromDate:startDate];
- NSDateComponents*comp2=[selfcomponents:unitsfromDateendDate];
- [comp1setHour:12];
- [comp2setHour:12];
- NSDate*date1=[selfdateFromComponents:comp1];
- NSDate*date2=[selfdateFromComponents:comp2];
- return[[selfcomponents:NSDayCalendarUnitfromDate:date1toDate:date2options:0]day];
- }
- @end
判断一个日期是否在当前一周内(使用格里高利历):[plain]viewplaincopy
- -(BOOL)isDateThisWeek:(NSDate*)date{
- NSDate*start;
- NSTimeIntervalextends;
- NSCalendar*cal=[NSCalendarautoupdatingCurrentCalendar];
- NSDate*today=[NSDatedate];
- BOOLsuccess=[calrangeOfUnit:NSWeekCalendarUnitstartDate:&startinterval:&extendsforDate:today];
- if(!success)
- returnNO;
- NSTimeIntervaldateInSecs=[datetimeIntervalSinceReferenceDate];
- NSTimeIntervaldayStartInSecs=[starttimeIntervalSinceReferenceDate];
- if(dateInSecs>dayStartInSecs&&dateInSecs<(dayStartInSecs+extends)){
- returnYES;
- }
- else{
- returnNO;
- }
- }