我正在开发应用程序,该应用程序已成功完成并上线。现在,我在该应用程序中发现了一个错误,因为我正在根据用户的当前时间管理项目。就像时间是用元素可用或不可用来定义的,元素只会在那个可用的时间可见。时间随该项目的 Web 服务响应一起发送。
格式如下:
"03:00 PM to 06:00 PM,06:30 PM to 07:30 PM"
我当前的代码如下:
BOOL isOkToProceed = NO;
NSDate *today = [[NSUserDefaults standardUserDefaults] objectForKey:@"server_date"];
NSArray *spliteTimearr = [vendorTimeToday componentsSeparatedByString:@","];
//"03:00 PM to 06:00 PM,06:30 PM to 07:30 PM";
for(int m=0;m<[spliteTimearr count];m++)
{
if([[spliteTimearr objectAtIndex:m] length] > 0)
{
NSArray *toSplitArr = [[spliteTimearr objectAtIndex:m] componentsSeparatedByString:@" to "];
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setTimeStyle:NSDateFormatterShortStyle];
[inputDateFormatter setDefaultDate:today];
// [inputDateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"hh:mm a" options:0 locale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]]];
//[inputDateFormatter setDateStyle:NSDateFormatterNoStyle];
//[inputDateFormatter setTimeZone:[NSTimeZone localTimeZone]];
[inputDateFormatter setDoesRelativeDateFormatting:YES];
NSDate *date1 = [inputDateFormatter dateFromString:[toSplitArr objectAtIndex:0]];
NSDate *date2 = [inputDateFormatter dateFromString:[toSplitArr objectAtIndex:1]];
if(([today isLaterThanOrEqualTo:date1]) && ([today isEarlierThanOrEqualTo:date2]))
{
isOkToProceed = YES;
break;
}
}
}
return isOkToProceed;
当我的 iPhone 的日期和时间为 12 小时格式时,此代码可以正常工作。但当 iPhone 的日期和时间格式为 24 小时时,它在 date1 和 date2 中返回 nil。
我尝试了很多选项,但都没有用。任何帮助将不胜感激。提前致谢。
最佳答案
在处理来自服务器的日期(应该全部采用 UTC)时,您需要使用 en_US_POSIX 语言环境。参见 this Apple tech note了解详情。
关于ios - NSDateFormatter : 12 hour formatted string can't converted in date when system date format is 24 hour in ios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35694248/