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

时间:2016-02-29 07:42:47

标签: ios nsdate nsdateformatter

我正在开发app,它已成功完成并变为现场。现在,我在该应用程序中发现了一个错误,因为我正在管理与用户当前时间相关的项目。就像使用或不使用项目定义时间一样,项目仅在该可用时间内可见。通过该项目的Web服务响应发送时间。

格式如下:

  

" 03:00 PM到06:00 PM,06:30 PM到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小时时,它会在nildate1中返回date2

我尝试了很多选择,但没有奏效。任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

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