我对已创建的日期进行了一些评论,因此我希望该日期为天数,之后为月份。这是我得到日期的代码:
NSDateFormatter * inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss" ];
NSString * inputString = entry.createdAt;
NSDate * inputDate = [inputFormatter dateFromString:inputString];
double timeInterval = [inputDate timeIntervalSinceNow];
dateLabel.text = [NSString stringWithFormat:@"%d",timeInterval];
答案 0 :(得分:1)
日子很简单:
int days = timeInterval / (60.0 * 60.0 * 24.0); //< i.e. divide by seconds in a day
月份更难。你想要它真的准确吗?或者假设一个月30天呢?如果是这样,那就是:
int months = timeInterval / (60.0 * 60.0 * 24.0 * 30.0); //< i.e. divide by seconds in a month
要将所有内容组合在一起,您可以这样做:
if (timeInterval < (60.0 * 60.0 * 24.0 * 30.0)) {
dateLabel.text = [NSString stringWithFormat:@"%i days", (int)(timeInterval / (60.0 * 60.0 * 24.0))];
} else {
dateLabel.text = [NSString stringWithFormat:@"%i months", (int)(timeInterval / (60.0 * 60.0 * 24.0 * 30.0))];
}
这就是你想要的吗?
答案 1 :(得分:0)
您应该查看NSCalendar components:fromDate:toDate:options方法。
NSDate *date = [[[NSDate alloc] init] autorelease];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date toDate:inputDate options:0];
int years = [components year];
int months = [components month];
int days = [components day];
NSLog(@"Start date: %@ End Date: %@", date, inputDate);
NSLog(@"year: %i months: %i days: %i", years, months, days);
[date release];
[calendar release];