我不明白两个日期的正确差异在哪里我错了,
-(void)updateTimeLabel{
NSString *serverResponseTimeString = @"02-08-2014 05:26:32";
NSString *systemDateString = @"02-08-2014 05:31:46";
NSDate *serverTime = [self dateFromWebStringResponse:serverResponseTimeString];
NSDate *systemDate = [self dateFromWebStringResponse:systemDateString];
NSLog(@"serverResponseTime %@", serverResponseTimeString);
NSLog(@"serverTime %@", serverTime);
NSLog(@"systemDate %@", systemDate);
NSLog(@"difference of time %d", [self differenceOfTimeInterval:systemDate toDate:serverTime]);
}
-(NSDate *)dateFromWebStringResponse:(NSString *)dateInString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm-dd-yyyy hh:mm:ss"];
NSDate *theDate = [dateFormatter dateFromString:dateInString];
return theDate;
}
-(NSInteger)differenceOfTimeInterval:(NSDate *)fromDate toDate:(NSDate *)toDate{
NSTimeInterval differenceOfIntervals = [toDate timeIntervalSinceDate: fromDate];
NSInteger minutes = floor(differenceOfIntervals/60);
return minutes;
}
输出: -
2014-02-08 17:58:57.185 iOSPractise[16770:907] serverResponseTime 02-08-2014 05:26:32
2014-02-08 17:58:57.186 iOSPractise[16770:907] serverTime 2014-01-07 23:56:32 +0000
2014-02-08 17:58:57.187 iOSPractise[16770:907] systemDate 2014-01-07 22:00:46 +0000
2014-02-08 17:58:57.188 iOSPractise[16770:907] difference of time 115
我希望有5分钟的差异。
答案 0 :(得分:2)
您的日期格式错误。月份的格式为“MM”(不是“mm”,即分钟),24小时格式为“HH”(“hh”表示上午12小时/下午时间):
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
另外,正如@Flexicoder所提到的,你应该指定一个“locale”独立于 用户的区域设置:
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
(请参阅http://www.flexicoder.com/blog/index.php/2013/10/ios-24-hour-date-format/或What is the best way to deal with the NSDateFormatter locale "feechur"?。)
答案 1 :(得分:0)
您的日期格式不正确。查看所有可能的说明符的链接:
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns