Pergunta

I use the below Utility method to display the seconds, minutes, hours, etc gone by.

e.g., 1 hour ago

I have a friend overseas testing our iPhone application and every time they submit an item the method always returns "1 hour ago" because New Zealand is 2 hours ahead and the server is hosted in Australia, which is obviously 2 hours behind.

It's only until our SQL Server catches up; when the item date starts to calculate properly.

Just wondering how I can handle time zone differences and modify my Utility method to work globally? Please feel free to help modify the method so it's not so many lines of code (if you're feeling really bored - and generous).

Thanks in advance.

+ (NSString *)elapsedTime:(NSDate *)date {
    NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components:desiredComponents
                                                                         fromDate:date
                                                                           toDate:[NSDate date]
                                                                          options:0];

    // Format to be used to generate string to display.
    NSString *scannedFormat = @"%d %@ ago";
    NSInteger number = 0;
    NSString *unit;

    if ([elapsedTimeUnits year] > 0) {
        number = [elapsedTimeUnits year];
        unit = [NSString stringWithFormat:@"year"];
    } else if ([elapsedTimeUnits month] > 0) {
        number = [elapsedTimeUnits month];
        unit = [NSString stringWithFormat:@"month"];
    } else if ([elapsedTimeUnits week] > 0) {
        number = [elapsedTimeUnits week];
        unit = [NSString stringWithFormat:@"week"];
    } else if ([elapsedTimeUnits day] > 0) {
        number = [elapsedTimeUnits day];
        unit = [NSString stringWithFormat:@"day"];
    } else if ([elapsedTimeUnits hour] > 0) {
        number = [elapsedTimeUnits hour];
        unit = [NSString stringWithFormat:@"hour"];
    } else if ([elapsedTimeUnits minute] > 0) {
        number = [elapsedTimeUnits minute];
        unit = [NSString stringWithFormat:@"minute"];
    } else if ([elapsedTimeUnits second] > 0) {
        number = [elapsedTimeUnits second];
        unit = [NSString stringWithFormat:@"second"];
    } else {
        number = 1;
        unit = @"second";
    }

    // Check if unit number is greater than 1, then append 's' at the end.
    if (number > 1) {
        unit = [NSString stringWithFormat:@"%@s", unit];
    }

    // Resultant string required.
    NSString *scannedString = [NSString stringWithFormat:scannedFormat, number, unit];

    return scannedString;
}

Nenhuma solução correta

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top