我有一个数据字典,如下所示:
{
asr = "4:23 pm";
dhuhr = "12:02 pm";
fajr = "1:17 am";
isha = "10:47 pm";
maghrib = "8:23 pm";
shurooq = "3:41 am";
}
我的目标是确定接下来的时间。我的计划是使用以下代码将这些转换为实际的NSDates:
//create an NSDate with todays date and the right prayer time
NSString *prayerDateString = [curDate stringByAppendingString: @" "];
prayerDateString = [prayerDateString stringByAppendingString: time];
NSLog(@"prayer date string: %@", prayerDateString);
//convert string back to date
NSDate *prayerDateAndTime = [dateAndTimeFormatter dateFromString:prayerDateString];
[dictionaryOfDatesAsDates addObject:prayerDateAndTime];
我认为哪个有效,但我不确定它是否正确保留了字典的格式。然后使用[currentDate timeIntervalSinceNow]
检查每一个并假设下一次最小的正时间间隔并获取名称,例如asr
。
我不确定如何进行迭代并将时间间隔值与时间名称一起存储,以便从中获取最小值?
我将如何实现这一目标?
答案 0 :(得分:2)
所以,你已经得到了你的日期并将它们添加到一个数组中:
NSArray *prayerDateAndTimes = ...
从昨天开始:
获取日期列表,然后使用NSPredicate将该列表过滤到日期> = [NSDate日期],然后按升序排序。然后,过滤后的排序数组中的第一项将是下一个日期。
首先,过滤掉已经过去的日期:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF >= %@", [NSDate date]];
NSArray *validPrayerDateAndTimes = [prayerDateAndTimes filteredArrayUsingPredicate:predicate];
现在我们可以判断今天是否还有更多日期:
if (validPrayerDateAndTimes.count > 0) {
// yay, sort to find the next one
validPrayerDateAndTimes = [validPrayerDateAndTimes sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"next date: %@", [validPrayerDateAndTimes objectAtIndex:0]);
} else {
NSLog(@":-(");
}
答案 1 :(得分:0)
编辑:
这应该有效。将字典更改为24小时格式(20:23)。它将返回具有最接近当前时间的密钥(即使它今天没有更多的祈祷,它将在第二天返回)。
-(NSDate*)initDateWithHour:(int)hour andMinutes:(int)minutes
{
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
NSDateComponents *nowComp = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
[components setYear:[nowComp year]];
[components setMonth:[nowComp month]];
[components setDay:[nowComp day]];
[components setHour:hour];
[components setMinute:minutes];
return [calendar dateFromComponents:components];
}
- (NSString*)getClosestTimeKey:(NSDictionary*)dict
{
NSDate* now = [NSDate date];
int secondsOfDay = 86400;
int minDif = secondsOfDay;
NSString* closestKey = @"";
for (NSString* key in dict)
{
NSString* timeStr = [dict objectForKey:key];
NSArray *array = [timeStr componentsSeparatedByString:@":"];
int hour = [[array objectAtIndex:0] intValue];
int minutes = [[array objectAtIndex:1] intValue];
NSDate *d = [self initDateWithHour:hour andMinutes:minutes];
int dif = [d timeIntervalSince1970] - [now timeIntervalSince1970];
if (dif < 0)
dif += secondsOfDay;
if (dif < minDif)
{
minDif = dif;
closestKey = key;
}
}
return closestKey;
}
你通过以下方式使用它:
NSString* key = [self getClosestTimeKey:dict];