我如何获得日期差异?
问题描述:
我正在计算testapp中两个日期之间的差异。它工作正常,如果我不改变月份,但当我改变月份不起作用。请帮我在这里是我正在使用的代码: -我如何获得日期差异?
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
//[df setDateStyle:NSDateFormatterMediumStyle];
df.dateFormat = @"YYYY-MM-DD";
NSDate *date1 = [df dateFromString:@"2011-04-30"];
NSDate *date2 = [df dateFromString:@"2011-05-03"];
NSLog(@"date1=%@",date1);
NSLog(@"date2=%@",date2);
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween/86400;
NSLog(@"There are %d days in between the two dates.", numberOfDays);
输出是-27。我很迷惑。
请人帮我解决这个问题..
答
试试这个
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
//[df setDateStyle:NSDateFormatterMediumStyle];
//df.dateFormat = @"yyyy-mm-dd";
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *date1 = [df dateFromString:@"2011-04-30"];
NSDate *date2 = [df dateFromString:@"2011-05-03"];
NSLog(@"date1=%@",date1);
NSLog(@"date2=%@",date2);
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween/86400;
NSLog(@"There are %d days in between the two dates.", numberOfDays);
调整时区来获取正确的日期......
答
你必须说的NSDate您使用的格式:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = @"yyyy'-'MM'-'dd";
NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; // Your locale
df.locale = local;
[local release];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; // Your timezone
NSDate *date1 = [df dateFromString:@"2011-04-30"];
NSDate *date2 = [df dateFromString:@"2011-05-03"];
[df release];
答
变化
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
到
NSTimeInterval secondsBetween = [date1 timeIntervalSinceDate:date2];
答
你也可以试试这个方法,从中可以从两个日期得到任何样的区别......
-(NSString *)timeSinceTimestamp:(NSString *)seconds
{
double seconds2 = [seconds doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds2];
NSDate *now = [NSDate date];
double start = [date timeIntervalSince1970];
double end = [now timeIntervalSince1970];
double difference = (end - start)/1000;
difference = round(difference);
int minutes = difference/60;
int hours = minutes/60;
int days = hours/24;
int weeks = days/7;
int months = weeks/5;
int years = months/12;
NSString *string;
if(difference < 60)
{
string = [NSString stringWithFormat:@"%i seconds ago",difference];
}
else if (minutes > 1 && minutes < 60)
{
string = [NSString stringWithFormat:@"%i minutes ago",minutes];
}
else if (hours > 1 && hours < 24)
{
string = [NSString stringWithFormat:@"%i hours ago",hours];
}
else if (days > 1 && days < 7)
{
string = [NSString stringWithFormat:@"%i days ago",days];
}
else if (weeks > 1 && weeks < 5)
{
string = [NSString stringWithFormat:@"%i weeks ago",weeks];
}
else if (months > 1 && months < 12)
{
string = [NSString stringWithFormat:@"%i months ago",months];
}
else if (years > 1 && years < 12)
{
string = [NSString stringWithFormat:@"%i years ago",years];
}
return string;
}