现在的位置: 首页 > 综合 > 正文

[iPhone][cocoa] 如何计算两个日期之间的天数

2013年12月05日 ⁄ 综合 ⁄ 共 2340字 ⁄ 字号 评论关闭

1: NSDate objects 
represent a single point in time.

2: NSDateComponents
NSDateComponents encapsulates the components of a date in an extendable, object-oriented manner.

3: NSCalendar
Calendars encapsulate information about systems of reckoning time in which the beginning, length, and divisions of a year are defined. They provide
information about the calendar and support for calendrical computations such as determining the range of a given calendrical unit and adding units to a given absolute time.


In a calendar, day, week, weekday, month, and year numbers are generally 1-based, but there may be calendar-specific exceptions.

To do calendar arithmetic, you use NSDate objects in conjunction with a calendar. For example, to convert between a decomposed date in one calendar
and another calendar, you must first convert the decomposed elements into a date using the first calendar, then decompose it using the second. NSDate provides the absolute scale and epoch (reference point) for dates and times, which can then be rendered into
a particular calendar, for calendrical computations or user display.


转换方法:

NSCalendar 类的
- (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts

获取startDate与endDate 之间相隔几天

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate  toDate:endDate  options:0];
int days = [comps day];


其他使用实例

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



提示:
1: NSDate 

To parse strings containing dates and to generate string representations of a date, you should use an instance of NSDateFormatter using the methods
dateFromString: and stringFromDate: respectively—see Date Formatters for more details.

转帖:http://o0o0o0o.iteye.com/blog/837634

可以这样做:

NSDate *dateFromString = [dateFormatter dateFromString:@"2012-05-10"];
NSDate *dateToString = [dateFormatter dateFromString:@"2012-07-12"];
int timediff = [dateToString timeIntervalSince1970]-[dateFromString timeIntervalSince1970];

计算结果的单位为秒,自己换算为天就行了。

转帖:http://www.cocoachina.com/bbs/read.php?tid=113371

抱歉!评论已关闭.