我的时间在下午5:30之后出现在iphone sdk上

时间:2015-03-05 10:19:38

标签: ios iphone nsdate nsdateformatter utc

我使用以下代码计算时差

NSString *strTemp = [[NSString alloc] initWithString:[dicTemp objectForKey:@"created_at"]];


NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

NSDateFormatter *dtFormatter = [[NSDateFormatter alloc] init];
dtFormatter.dateFormat = [NSString stringWithFormat:DATEFORMAT_TYPE];
[dtFormatter setLocale:locale];

[dtFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSDate *dt = [dtFormatter dateFromString:strTemp];

NSDateFormatter *todayFormatter = [[NSDateFormatter alloc] init];
[todayFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
todayFormatter.dateFormat = DATEFORMAT_TYPE;
[todayFormatter setLocale:locale];

NSString *strToday = [todayFormatter stringFromDate:[NSDate date]];
NSDate *today = [todayFormatter dateFromString:strToday];

NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:NSCalendarUnitHour fromDate:dt toDate:today options:0];
NSDateComponents *componentsMinute = [c components:NSCalendarUnitMinute fromDate:dt toDate:today options:0];

NSInteger diffHours = components.hour;
NSInteger diffMinutes = componentsMinute.minute;

在向服务器发送日期时,我按以下方式发送:

NSDate *date = [NSDate date];
NSDateFormatter *dateFormate = [[NSDateFormatter alloc] init];
[dateFormate setDateFormat:DATEFORMAT_TYPE];
[dateFormate setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormate setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *strCurrentDate = [dateFormate stringFromDate:date];

我从发送的服务器获得相同的日期,同时将nsdate转换为获取当前日期以计算小时数,我总是开始得到负时间,即小时差异为负,我注意到它发生在下午5:30之后在印度,在此之前它是正确的。

请帮助。

1 个答案:

答案 0 :(得分:1)

您的问题在于差异计算。我们举三个例子。相隔30分钟的日期,相隔60分钟的日期和相隔90分钟的日期。


NSDateComponents *components = [c components:NSCalendarUnitHour fromDate:dt toDate:today options:0];

此代码计算两个日期之间的小时数差异。 0表示第一个例子(30分钟),1表示第二个例子(60分钟),1表示第三个例子(90分钟)。

NSDateComponents *componentsMinute = [c components:NSCalendarUnitMinute fromDate:dt toDate:today options:0];

此代码计算两个日期之间的分钟差异。它不会忽略小时数。它将为您提供日期之间的所有分钟,因此结果可以大于59.第一个示例为30(30分钟),第二个示例为60(60分钟),第三个示例为90(90分钟)。

如果您认为使用60*diffHours + diffMinutes获得会议记录,那么每次差异不会少于60分钟,您的结果就会出错。 60分钟你会计算:60 * 1 + 60是120,而不是60. 90分钟你会计算出:60 * 1 + 90是150,而不是90.

我不确定你需要什么输出。如果您只需要几分钟就可以删除第一个电话。

如果您需要更多组件,您应该将NSCalendarUnits组合在一起:

NSDateComponents *components = [c components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:dt toDate:today options:0];

NSInteger diffHours = components.hour;
NSInteger diffMinutes = components.minute;

使用此方法计算差异时,日历将在计算较小单位时考虑较大的单位。仅使用剩余部分,即结果将是hour = 1 and minute = 30 90分钟。