Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

ios - Create NSDate from 24h NSString return null

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];
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...