如何准确完成日期?
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:[dateFormatter dateFromString:startDate]
toDate:[dateFormatter dateFromString:endDate]
options:0];
return (CGFloat)components.day;
}
工作完成3天12小时30分钟 预期结果3.55天。
答案 0 :(得分:0)
以下示例显示了与给定日期和今天的天数差异。
这可能会指导您将秒,分钟,小时转换为天。
-(NSString*)timeDifferenceConversion:(NSString*)dateString
{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* firstDate = [dateFormatter dateFromString:dateString];
NSDate * now = [NSDate date];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *newDateString = [dateFormatter stringFromDate:now];
NSDate* secondDate = [dateFormatter dateFromString:newDateString];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSInteger ti = (NSInteger)timeDifference;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
NSInteger days = (ti / 86400);
NSString* temp=@"";
if(minutes<=2 && hours<1 && days<1)
{
temp=@"now";
}
else if(minutes>2 && hours<1 && days<1)
{
temp=[NSString stringWithFormat:@"%ld minutes ago", (long)minutes];
}
else if(hours<=24 && days<1)
{
temp=[NSString stringWithFormat:@"%ld hours ago", (long)hours];
}
else if(days<=1)
{
temp=[NSString stringWithFormat:@"%ld day ago",(long)days];
}
else if(days>1)
{
temp=[NSString stringWithFormat:@"%ld days ago",(long)days];
}
return temp;
}
答案 1 :(得分:0)
我建议你计算两个日期之间的秒数差异,然后简单地将结果除以一天中的秒数:
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDate *date1 = [NSDate dateWithString: startDate];
NSDate *date2 = [NSDate dateWithString: endDate];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
return secondsBetween / 86400.0f;
}