我需要在几分钟内计算两天之间的差异。
NSDate *now = [[NSDate alloc] init];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[outputFormatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
NSString* dateStringFromDatabase = @"01/01/1900 11:00:00 AM";
NSDate* dateFromString = [outputFormatter dateFromString:dateStringFromDatabase];
NSString* a = [outputFormatter stringFromDate:now];
NSDate* b = [outputFormatter dateFromString:a];
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:dateFromString
toDate:b options:0];
int hours = [components hour];
int minutes = [components minute];
self.lblResult.text = [NSString stringWithFormat:@"%i:%i", hours, minutes];
但我有以下问题: 目前的时间我得到:
2012-10-21 07:37:09 +0000 // wrong it's two hours late
当我尝试将@"01/01/1900 11:00:00 AM"
投射到NSDate
时,我得到了
1900-01-01 10:00:00 +0000 // also two hours late
答案 0 :(得分:1)
您需要设置-dateStyle
而不是时间样式,因为该字符串中还包含日期。
编辑---
您现在需要将-dateFormat
更改为dd/MM/yyyy HH:mm:ss a
答案 1 :(得分:1)
试试这..................
如果您在String中有日期,请使用@"dd/MM/yyyy hh:mm:ss a"
NSDate *startDate = ...;
NSDate *endDate = ...;
现在日期比较
// Date Comparision
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:LastDate
toDate:CuurentDate options:0];
获取两个日期之间的差异
int months = [components month];
int days = [components day];
int hours = [components hour];
int minutes = [components minute];
答案 2 :(得分:0)
我希望这会有所帮助
NSString *dtString = @"1900-01-01T11:00:00";
dtString = [dtString stringByReplacingOccurrencesOfString:@"T" withString:@" "];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *currentTime = [dateFormatter stringFromDate:today];
NSDate *toTimeDate = [dateFormatter dateFromString:dtString];
NSString *toTime = [dateFormatter stringFromDate:toTimeDate];