我使用下面的代码来准确地在下午5点IST发起localNotification。但是当记录fireDate时,它并没有显示我想要的时间。我是否在任何地方出错了?
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//localNotification.fireDate = myNewDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
NSDate *currentDate = [NSDate date];
NSDate *fireDate = nil;
//[dateComponents setDay:3]; // ...or whatever day.
[dateComponents setHour:11];
[dateComponents setMinute:30];
fireDate = [calendar dateByAddingComponents:dateComponents
toDate:currentDate
options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//Optionally for time zone converstions
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
NSString *stringFromDate = [formatter stringFromDate:fireDate];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:stringFromDate];
NSLog(@"Fire date : %@",dateFromString);
[localNotification setFireDate:dateFromString];
我的输出: 开火日期: 2014-07-29 16:48:20 +0000
答案 0 :(得分:0)
你没有得到5PM的原因是代码中没有任何东西试图将时间设置为下午5点。相反,你有这个:
[dateComponents setHour:11];
[dateComponents setMinute:30];
fireDate = [calendar dateByAddingComponents:dateComponents
toDate:currentDate
options:0];
这对你来说是未来11小时30分钟的时间。除非您恰好在凌晨5:30运行代码,否则您不会获得5PM。但是代码在任何地方都没有提到IST
,因此你不会在该区域获得5PM。
这也会让你在代码片段末尾所做的事情变得混乱 - 将fireDate
转换为字符串,然后将该字符串转换回日期。这没有任何意义。
要在特定时区内获得下午5点,您需要执行以下操作。这将在所请求的时区内接下来的下午5点,如果它已经在下午5点之后可能是明天:
NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"Asia/Kolkata"];
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:zone];
NSInteger targetHour = 17; // 5pm
NSDate *now = [NSDate date];
NSInteger componentFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit;
NSDateComponents *nowDateComponents = [calendar components:componentFlags fromDate:now];
if (nowDateComponents.hour >= targetHour) {
nowDateComponents.day += 1;
}
nowDateComponents.hour = targetHour;
NSDate *targetDate = [calendar dateFromComponents:nowDateComponents];
如果您想以人类可读的形式打印,可以执行以下操作。但NSDateFormatter
只是向用户提供日期所必需的 - 它不是获得所需NSDate
的一部分。
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:zone];
[formatter setDateStyle:NSDateFormatterLongStyle];
[formatter setTimeStyle:NSDateFormatterLongStyle];
NSString *targetDateString = [formatter stringFromDate:targetDate];
NSLog(@"Target date: %@", targetDateString);