Create NSDate from 24h NSString return null

折月煮酒 提交于 2019-12-13 08:57:28

问题


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:


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];


来源:https://stackoverflow.com/questions/29161343/create-nsdate-from-24h-nsstring-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!