obj-C, почему это дает мне вчерашнюю дату? - PullRequest
0 голосов
/ 26 августа 2011

Я изо всех сил пытался вернуть текущую дату как можно ближе к нулю секунд, минут и часов, насколько это возможно. Поэтому я могу повторно использовать одну и ту же дату в различных транзакциях.

Однако теперь я обнаружил, что моя функция возвращает дату вчерашнего дня?

+ (NSDate *)makeAbsoluteNSDate:(NSDate*)datSource {

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:
           NSGregorianCalendar];
    [calendar setTimeZone:[NSTimeZone localTimeZone]];

    NSDateComponents *dateComponents = [calendar components:NSYearCalendarUnit | 
            NSMonthCalendarUnit | NSDayCalendarUnit
            fromDate:datSource];
    [dateComponents setHour:0];
    [dateComponents setMinute:0];
    [dateComponents setSecond:0];

    NSDate *today = [calendar dateFromComponents:dateComponents];
    [calendar release];

    return today;
}

Ответы [ 3 ]

5 голосов
/ 26 августа 2011

Если вы пытаетесь получить сегодняшнюю или вчерашнюю полночь в вашем часовом поясе, вы должны получить NSDate, что указывает на адекватное время в GMT . В моем случае -2 часа, поскольку мой часовой пояс +0200, поэтому в полночь 2011-08-26 я получу 2011-08-25 22: 00.

Вы должны убедиться, что вы устанавливаете правильный часовой пояс для NSCalendar, который равен [NSTimeZone systemTimeZone].

Моя процедура получения полуночи в моем часовом поясе:

+ (NSDate *)midnightOfDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone systemTimeZone]];

    NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
    [components setTimeZone:[cal timeZone]];

    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];

    return [cal dateFromComponents:components];
}

Итак, после длинного обсуждения в комментариях, вот функция полудня:

+ (NSDate *)middayOfDate:(NSDate *)date {
    NSCalendar *cal = [NSCalendar currentCalendar];
    [cal setTimeZone:[NSTimeZone systemTimeZone]];

    NSDateComponents *components = [cal components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
    [components setTimeZone:[cal timeZone]];

    [components setHour:12];
    [components setMinute:0];
    [components setSecond:0];

    return [cal dateFromComponents:components];
}
0 голосов
/ 26 августа 2011

Используйте функцию ниже, чтобы получить дату вчерашнего дня:

- (NSDate *)getDate:(NSDate *)date days:(NSInteger)days hours:(NSInteger)hours mins:(NSInteger)mins seconds:(NSInteger)seconds 
{
     NSCalendar *cal = [NSCalendar currentCalendar];
     NSDateComponents *components = [cal components:( NSHourCalendarUnit |   NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];

     days = (days*24) + hours; 
     [components setHour:days];
     [components setMinute:mins];
     [components setSecond:seconds];

     NSDate *returnDate = [cal dateByAddingComponents:components toDate:date options:0];
     return returnDate;
 }

Чтобы получить дату передачи вчерашней даты = [NSDate date], день = -1, часы = 0 и mins = 0 в качестве параметров при вызове метода.

0 голосов
/ 26 августа 2011

Все, что вам нужно, это [NSDate date] для текущей даты и времени.

...