Create NSDate from 24h NSString return null

2019-09-19 12:49发布

I have NSString in 24h format like that:

NSString *a = @"10:00";
NSString *b = @"23:59";

How can I get NSDate with NSString b?

I using:
+ setDateFormat: @"HH:mm" ==> It's work both for a and b when phone setting is 24h.
+ setDateFormat: @"hh:mm" ==> It's only work for a when phone setting is am/pm.

My full code, with self.timeInit is NSString with 24h format:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"HH:mm"];
    NSDate *date = [dateFormat dateFromString:self.timeInit];

    if (!date){
        [dateFormat setDateFormat:@"hh:mm"];
        date = [dateFormat dateFromString:self.timeInit];
        NSLog(@"Date 2: %@", date);
    }

    if (!date){
        [dateFormat setDateFormat:@"H:mm"];

        date = [dateFormat dateFromString:self.timeInit];
        NSLog(@"Date 3: %@", date);
    }

    NSLog(@"Date: %@", date);
    if (date){
        [self.timePickerUI setDate:date];
    }

1条回答
我命由我不由天
2楼-- · 2019-09-19 13:17

You force your own locale on the NSDateFormatter, so it ignores the settings of the user.

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"HH:mm"];
[dateFormat setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *date = [dateFormat dateFromString:self.timeInit];
查看更多
登录 后发表回答