0

我需要以分钟为单位计算两天之间的差异。

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
4

3 回答 3

1

您需要设置-dateStyle而不是时间样式,因为该字符串中还包含一个日期。

编辑 - -

您现在需要-dateFormatdd/MM/yyyy HH:mm:ss a

于 2012-10-19T12:48:37.403 回答
1

尝试这个..................

如果您在字符串中有日期,则使用将其转换为日期@"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];
于 2012-10-20T13:02:54.037 回答
0

I hope this helps

    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];
于 2012-10-19T13:08:01.400 回答