Uilocalnotification & nstimezone, неправильный часовой пояс, появляющийся

StackOverflow https://stackoverflow.com/questions/9316332

Вопрос

Я стараюсь здесь установить тревогу. Я нахожусь в Монреале, так что в часовом поясе EST. В коде, который я использую, я получаю текущую дату и стараюсь, чтобы она позвонила несколько минут спустя. Код работает совершенно нормально, а тревога звонит, как и ожидалось.

Вот проблема: сейчас 12.41. Тревога будет звонить в 12.43. Однако в моем NSLOG время напечатано: Уволить: 2012-02-16 17:43:00 +0000

Это не является серьезной проблемой, поскольку она работает, но есть идеи о том, почему он показывает в то время и до сих пор работает? Есть идеи о том, как это исправить? Спасибо!

Я в основном положил часовой пояс повсюду, вот код, который я использую:

-(void) Schedulenotification Withithinterval: (int) минуты до {

// Current date
NSDate *now = [NSDate date];
// Specify which units we would like to use
unsigned units = NSTimeZoneCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSTimeZone* zone = [NSTimeZone timeZoneWithName:@"EST"];
[calendar setTimeZone:zone];
NSDateComponents *components = [calendar components:units fromDate:now];
[components setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];

NSInteger year = [components year];
NSInteger month = [components month];
NSInteger day = [components day];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setYear:year];
[dateComps setMonth:month];
[dateComps setDay:day];
[dateComps setHour:hour];
[dateComps setMinute:minute+2]; // Temporary
NSDate *itemDate = [calendar dateFromComponents:dateComps];

NSLog(@"fireDate : %@", itemDate);

UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
    return;
localNotif.fireDate = itemDate;
//localNotif.timeZone = zone;
localNotif.timeZone = [NSTimeZone timeZoneWithName:@"EST"];

minutesBefore = 15; // Temporary
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"%@ in %i minutes.", nil),
                        @"Blabla", minutesBefore];
localNotif.alertAction = NSLocalizedString(@"See Foo", nil);

localNotif.soundName = UILocalNotificationDefaultSoundName;

NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"LastCall" forKey:@"lastcall"];
localNotif.userInfo = infoDict;

[[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 

}

Спасибо!

Это было полезно?

Решение

Обратите внимание на +0000 в конце? Это часовой пояс. Это говорит вам, что он позвонил в 17:43 по Гринвичу. Во -первых, чтобы установить часовой пояс, вам нужно использовать «Америка/Монреаль» (не EST) или использовать timeZoneWithAbbreviation: с Est. DateComponent настроен в любое время, которое вы установили и во времена вашего календаря. Вот почему дата верна, просто не отображается в нужном часового пояса. Чтобы изменить это, вам нужно использовать NSDateFormatter. Анкет Смотрите пример ниже для того, как!

 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSTimeZone* zone = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
[calendar setTimeZone:zone];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setHour:16];
[dateComps setYear:2001];
[dateComps setMinute:30];
NSDate *itemDate = [calendar dateFromComponents:dateComps];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeStyle:NSDateFormatterFullStyle];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"EST"]];

NSLog(@"fireDate : %@", [formatter stringFromDate:itemDate]);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top