Hours in NSDate every time in 24-hour style?

前端 未结 5 1621
小鲜肉
小鲜肉 2021-02-05 16:56

I have this date formatter:

 NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
 [timeFormatter setDateFormat:@\"HH:mm\"];

If I u

相关标签:
5条回答
  • 2021-02-05 17:17

    You have to two steps here

    NSLocale* locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
    [formatter setLocale:locale];
    
    [formatter setDateFormat:@"hh:mm a"];
    

    here a in the formatter gives am/pm format

    0 讨论(0)
  • 2021-02-05 17:20

    From Apple Documentation, the time formatting strings follow Unicode Technical Standard #35.

    As stated in UTR #35, uppercase HH gives you 24-hour style time while lowercase hh gives you 12-hour style time.

    In short, if you need 24-hour style, use [timeFormatter setDateFormat:@"HH:mm"]; and if you need 12-hour style, use [timeFormatter setDateFormat:@"hh:mm"];

    0 讨论(0)
  • 2021-02-05 17:21

    If you want to force it to 12-hour or 24-hour mode, regardless of the user's 24/12 hour mode setting, you should set the locale of the date formatter to en_US_POSIX (for 12-hour), or, say, en_GB for the 24-hour mode.

    That is,

    NSLocale* formatterLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"] autorelease];
    [timeFormatter setLocale:formatterLocale];
    

    Some more on that here:

    http://developer.apple.com/iphone/library/qa/qa2010/qa1480.html

    0 讨论(0)
  • 2021-02-05 17:25

    If it helps anyone I have just had an issue where I want to display the time for the user in the way they have set on their device:

    let timeFormatter = NSDateFormatter()
    timeFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
    //get the time from the picker
    

    The send the time to our API in 24 style:

    timeFormatter.locale = NSLocale(localeIdentifier: "en_GB")
    //get the time again
    
    0 讨论(0)
  • 2021-02-05 17:36

    I had this same issue recently and came across this document which lists all the date format patterns: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns

    I was able to get 24-times working just by using k:mm as the date format:

    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"k:mm"];
    
    0 讨论(0)
提交回复
热议问题