【发布时间】:2014-06-01 14:18:12
【问题描述】:
我正在尝试在 iOS 设备的 Objective-C (XCode) 中执行 segue,此时时间介于另外两个固定时间之间。就像商店的“营业时间”一样 - 现在的时间介于营业时间和关闭时间之间。
这是我一直在处理的代码 - 一些代码可能看起来很熟悉,因为我在 SO 上找到了一些有用的东西,对我有帮助 - 但我仍然无法让它工作。当时间超过 startTime 时,它不会执行 segue。应该在指定的时间间隔内。
时间为 24 小时制。
// set start time and end time
NSString *startTimeString = @"23:00";
NSString *endTimeString = @"05:00";
// set date formatter 24-hour format
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"HH:mm"];
// german timezone
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"de_DE"];
NSString *nowTimeString = [formatter stringFromDate:[NSDate date]];
// set NSDates for startTime, endTime and nowTime
NSDate *startTime = [formatter dateFromString:startTimeString];
NSDate *endTime = [formatter dateFromString:endTimeString];
NSDate *nowTime = [formatter dateFromString:nowTimeString];
[formatter setLocale:locale];
// compare endTime and startTime with nowTime
NSComparisonResult result1 = [nowTime compare:endTime];
NSComparisonResult result2 = [nowTime compare:startTime];
if ((result1 == NSOrderedDescending) &&
(result2 == NSOrderedAscending)){
NSLog(@"Time is between");
[self performSegueWithIdentifier:@"openHours" sender:self];
} else {
NSLog(@"Time is not between");
}
- 感谢您抽出宝贵时间查看我的问题。我一直在寻找和寻找,尝试和尝试,但还没有让它发挥作用。希望您的回答对我有所帮助。
【问题讨论】:
-
添加一些中间值的 NSLog,以便您了解发生了什么。由于您没有指定日期,因此 NSDate 值将是某年的 1 月 1 日(2000 年?)。另请注意,您的开始时间晚于结束时间,这可能意味着您的“商店”在午夜之前营业并一直营业到凌晨 5 点。如果这是您的意图,您可能需要反转比较的方向。
-
(在这样的情况下,在不了解代码在做什么的情况下复制代码通常是不好的。)
-
嗨热舔,是的。这一年是 2000 年,实际上也是 12 月。 31. 1999 - nowTime 跨越两天。是的,我试图扭转时间跨度,因为我发现 05:00 早于 23:00,但仍然没有运气..
-
“没有运气”是什么意思?
标签: ios objective-c nsdate