在 IST 下午 5 点准确触发 localNotification
-
21-12-2019 - |
题
我正在使用下面的代码片段在 IST 下午 5 点准确地触发 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
解决方案
您没有得到 5PM 的原因是代码中没有任何内容尝试将时间设置为 5PM。相反,你有这个:
[dateComponents setHour:11];
[dateComponents setMinute:30];
fireDate = [calendar dateByAddingComponents:dateComponents
toDate:currentDate
options:0];
这给你带来的是未来 11 小时 30 分钟的时间。除非您恰好在上午 5:30 运行代码,否则您不会得到下午 5 点。但代码没有提到 IST
任何地方,这样你就不会在那个区域得到下午 5 点的时间。
这也让你在代码片段末尾所做的事情感到困惑——转换 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);
不隶属于 StackOverflow