我有这个字符串,它被传递给这个方法以产生 2 次:
周一至周五上午 7:00 - 晚上 10:00
-(void)dealWithTimeStrings2:(NSString*)timeString{
NSString *s = timeString;
NSCharacterSet *digits = [NSCharacterSet decimalDigitCharacterSet];
int idx = [s rangeOfCharacterFromSet:digits].location;
NSString *timeStr = [s substringFromIndex:idx];
NSArray *timeStringsArray2 = [timeStr componentsSeparatedByString:@" - "];
NSLog(@"timeStringsArray2 %@", timeStringsArray2);
//NOW TURN INTO DATE AND FORMAT TO 24HR
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];
NSString *openDateString = (NSString*)[timeStringsArray2 objectAtIndex:0];
NSString *closeDateString = (NSString*)[timeStringsArray2 objectAtIndex:1];
NSLog(@"someDateString %@,%@", openDateString,closeDateString);
NSDate *openDate = [dateFormatter dateFromString:openDateString];
NSDate *closeDate = [dateFormatter dateFromString:closeDateString];
NSLog(@"open, now, close %@,%@,%@", openDate,[NSDate date],closeDate);
}
这会产生:
timeStringsArray2 ( "7:00 AM", "10:00 PM" )
someDateString 上午 7:00,晚上 10:00
打开,现在,关闭 2000-01-01 13:00:00 +0000,2013-07-24 23:51:55 +0000,2000-01-02 04:00:00 +0000
这是测试代码:
-(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2{
NSDate *now = [NSDate date];
BOOL inBetween = ([now compare:date1] == NSOrderedDescending && [now compare:date2] == NSOrderedAscending);
return inBetween;
}
如您所见,23:46 不在 6:00 和 18:00 之间。然而,我只是在我的时间 5:46 运行这个,也就是在上午 7:00 到晚上 10:00 之间。