NSDateFormatter, am I doing something wrong or is this a bug?

后端 未结 8 982
-上瘾入骨i
-上瘾入骨i 2020-11-30 06:18

I\'m trying to print out the date in a certain format:

NSDate *today = [[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]         


        
8条回答
  •  -上瘾入骨i
    2020-11-30 07:07

    The reason for this behaviour is Locale, It sets the correct Locale.

    Set the local of your NSDateFormatter to en_US_POSIX will fix this. It works for both 24-hour and 12 hour format.

    On iPhone OS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set. From apple doc

    Try this,

    NSDate *today = [[NSDate alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *dateStr = [dateFormatter stringFromDate:today];
    

提交回复
热议问题