我有这个字符串传递给这个方法产生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点”)
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之间。
答案 0 :(得分:0)
根本不需要日期或日期格式化程序。您可以使用字符串处理代码读取时间来获取小时和分钟信息。然后,您可以获取当前日期的日期组件以进行比较。