NSDateFormatter:当系统日期格式为 24 小时 ios 时,12 小时格式字符串无法转换为日期

NSDateFormatter : 12 hour formatted string can't converted in date when system date format is 24 hour in ios

我正在开发应用程序,该应用程序已成功完成并上线。现在,我在该应用程序中发现了一个错误,因为我正在根据用户的当前时间管理项目。就像时间是用物品可用或不可用来定义的,物品只会在那个可用的时间可见。时间随该项目的 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 小时格式时,此代码可以正常工作。但是 return nildate1date2 中 iPhone 的日期和时间格式是 24 小时。

我尝试了很多选项但都没有用。任何帮助将不胜感激。提前致谢。

处理来自服务器的日期(应该全部采用 UTC)时,您需要使用 en_US_POSIX 语言环境。有关详细信息,请参阅 this Apple tech note