我正在尝试在iOS应用上创建一个catch,以防止人们访问小窗口之外的内容。
基本上,我需要采取的行动只有在伦敦星期日(BST时区)的12-1:30 PM之间才会开火。我如何检查当前时间,将其转换为该时区,然后查看它是否匹配?
我尝试过以下操作,但它总是显示它在该范围之间:
- (NSDate *)dateByNeutralizingDateComponentsOfDate:(NSDate *)originalDate {
NSCalendar *gregorian = [[[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
// Get the components for this date
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: originalDate];
// Set the year, month and day to some values (the values are arbitrary)
[components setYear:2000];
[components setMonth:1];
[components setDay:1];
return [gregorian dateFromComponents:components];
}
- (BOOL)isTimeOfDate:(NSDate *)targetDate betweenStartDate:(NSDate *)startDate andEndDate:(NSDate *)endDate {
if (!targetDate || !startDate || !endDate) {
return NO;
}
// Make sure all the dates have the same date component.
NSDate *newStartDate = [self dateByNeutralizingDateComponentsOfDate:startDate];
NSDate *newEndDate = [self dateByNeutralizingDateComponentsOfDate:endDate];
NSDate *newTargetDate = [self dateByNeutralizingDateComponentsOfDate:targetDate];
// Compare the target with the start and end dates
NSComparisonResult compareTargetToStart = [newTargetDate compare:newStartDate];
NSComparisonResult compareTargetToEnd = [newTargetDate compare:newEndDate];
return (compareTargetToStart == NSOrderedDescending && compareTargetToEnd == NSOrderedAscending);
}
-(void)checkDate {
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEEE HH:mm"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:@"BST"];
[dateFormatter setTimeZone:timeZone];
NSDate *openingDate = [dateFormatter dateFromString:@"Sunday 12:00"];
NSDate *closingDate = [dateFormatter dateFromString:@"Sunday 1:30"];
NSDate *targetDate = [NSDate date];
if ([self isTimeOfDate:targetDate betweenStartDate:openingDate andEndDate:closingDate]) {
NSLog(@"TARGET IS INSIDE!");
}else {
NSLog(@"TARGET IS NOT INSIDE!");
}
}
答案 0 :(得分:1)
我假设您想要使用当前在英格兰观察的时间,而不是BST,因为BST是英国夏天时间。我的理解是,在冬季,他们使用UTC(以前称为GMT)。因此,我们应该以一种方式指定时区,该方式将根据一年中的时间从UTC中选择适当的偏移量。
static BOOL dateIsAcceptable(NSDate *date) {
NSCalendar *calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
calendar.timeZone = [NSTimeZone timeZoneWithName:@"Europe/London"];
NSDateComponents *components = [calendar
components:NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute
fromDate:date];
if (components.weekday != 1) {
return NO;
}
double hour = components.hour + components.minute / 60.0;
return hour >= 12 && hour < 13.5;
}