jjzjj

objective-c - NSDateFormatter stringFromDate 在使用 12 小时时间格式时返回 nil

coder 2024-01-21 原文

以下代码适用于 24 小时时间格式。

+ (NSString *)formatDate:(NSDate *)date useLongStyle:(BOOL)useLongStyle showDate:(BOOL)showDate showTime:(BOOL)showTime
{
    NSDateFormatter *dateFormatter = [NSDateFormatter new];

    dateFormatter.dateStyle = (useLongStyle) ? NSDateFormatterLongStyle : NSDateFormatterShortStyle;
    dateFormatter.dateStyle = (showDate) ? dateFormatter.dateStyle : NSDateFormatterNoStyle;
    dateFormatter.timeStyle = (showTime) ? NSDateFormatterShortStyle : NSDateFormatterNoStyle;

    return [dateFormatter stringFromDate:date];
}

但是当手机设置中有12小时格式时,返回nil。直到我明确地将区域设置为例如澳大利亚。

date 中的时间采用 24 小时格式。当前语言环境是 ru_RU(但在 en_EN 中是一样的)。

最佳答案

你可以用这个

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [formatter setLocale:locale];

关于objective-c - NSDateFormatter stringFromDate 在使用 12 小时时间格式时返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11414288/

有关objective-c - NSDateFormatter stringFromDate 在使用 12 小时时间格式时返回 nil的更多相关文章

随机推荐