我有两次存储在 NSDictionary 中。 “开始时间”为 22:30,“结束时间”为凌晨 4:00。
我需要弄清楚当前时间是在开始时间之前、结束时间之前,还是在结束时间之后和下一次开始时间之前。
我确信我把事情弄得比需要的复杂得多,但在试图掩盖所有可能性的过程中,我把自己搞糊涂了。
NSDictionary *noaudio = [[NSUserDefaults standardUserDefaults] objectForKey:@"NoSound"];
NSDateFormatter *tformat = [[NSDateFormatter alloc] init];
[tformat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[tformat setDateFormat:@"HH:mm"];
date1 = [tformat dateFromString:[noaudio objectForKey:@"start"]];
date2 = [tformat dateFromString:[noaudio objectForKey:@"end"]];
date3 = [NSDate date];
我是否必须对照日期 3 检查日期 1 和 2?
感谢您对此的任何指导。
最佳答案
好吧,只有两个时间,没有日期,你只能找出当前时间是否在开始时间和结束时间之间。这是因为,在您上面的示例中(开始时间 22:30 和结束时间 04:00)您将在 13:00 返回什么?今天是“结束时间之后”(04:00) 和“开始时间之前”(22:30)。
也就是说,这是一种检查当前时间是否在两个日期指定时间之间的方法。您可以通过将所有内容都保留为 NSDate(使用日历操作)来做到这一点,但这会使它变得更加复杂,因为您必须使用今天的日期和指定时间创建新的 NSDate 对象。这并不太难,但除非您在其他地方使用它们,否则没有理由这样做。
// Take a date and return an integer based on the time.
// For instance, if passed a date that contains the time 22:30, return 2230
- (int)timeAsIntegerFromDate:(NSDate *)date {
NSCalendar *currentCal = [NSCalendar currentCalendar];
NSDateComponents *nowComps = [currentCal components:NSHourCalendarUnit|NSMinuteCalendarUnit fromDate:date];
return nowComps.hour * 100 + nowComps.minute;
}
// Check to see if the current time is between the two arbitrary times, ignoring the date portion:
- (BOOL)currentTimeIsBetweenTimeFromDate1:(NSDate *)date1 andTimeFromDate2:(NSDate *)date2 {
int time1 = [self timeAsIntegerFromDate:date1];
int time2 = [self timeAsIntegerFromDate:date2];
int nowTime = [self timeAsIntegerFromDate:[NSDate date]];
// If the times are the same, we can never be between them
if (time1 == time2) {
return NO;
}
// Two cases:
// 1. Time 1 is smaller than time 2 which means that they are both on the same day
// 2. the reverse (time 1 is bigger than time 2) which means that time 2 is after midnight
if (time1 < time2) {
// Case 1
if (nowTime > time1) {
if (nowTime < time2) {
return YES;
}
}
return NO;
} else {
// Case 2
if (nowTime > time1 || nowTime < time2) {
return YES;
}
return NO;
}
}
关于ios - 检查时间是在两次保存的文本字符串时间之前还是之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10627062/