gpt4 book ai didi

iOS:从 NSDate 获取本地化时间

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:15:16 28 4
gpt4 key购买 nike

如何仅从 NSDate 获取本地化时间,对应于用户在设备上设置的 12 小时/24 小时时间?考虑日期是“2015 年 6 月 3 日下午 3:00”如果设置了 12 小时格式,那么它应该显示下午 3 点(不包括分钟部分)如果设置了 24 小时格式,那么它应该显示 15(不包括分钟部分)

我已尝试在所有语言环境中进行以下操作但均未成功。例如,它对 de_DE 和 fr_FR 非常有效,但对于 en_US,它总是返回 3,没有 AM/PM。

NSDateFormatter *dateFormatter = [NSDateFormatter new];
NSString *localeFormatString = [NSDateFormatter dateFormatFromTemplate:@"HH" options:0 locale:dateFormatter.locale];
dateFormatter.dateFormat = localeFormatString;
dateFormatter.timeZone = [NSTimeZone defaultTimeZone];

NSString * hour = [dateFormatter stringFromDate:date];
NSLog(@"%@",hour);

附言如果我使用以下代码获得时间字符串(小时和分钟),它在语言环境和 12/24 小时时间格式方面完美工作。但是我只想获得小时数,而 12/24 小时时间格式无法实现。

  NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.timeStyle = NSDateFormatterShortStyle;
timeFormatter.dateFormat = NSDateFormatterNoStyle;
timeFormatter.AMSymbol = @"a";
timeFormatter.PMSymbol = @"p";

timeFormatter.timeZone = timeZone;
return [timeFormatter stringFromDate:date];

最佳答案

这有点 hack,但可以通过以下方式获得本地化的小时字符串,例如“5 PM”或“17”(取决于用户的区域设置):

  1. 用所需的小时构建一个 NSDate,并将分钟设置为 0;
  2. 使用 NSDateFormatter 使用日期样式 NSDateFormatterNoStyle 和时间样式 NSDateFormatterShortStyle 获取该日期的本地化字符串表示;
  3. 从字符串中手动删除 :00(如果需要)。

代码:

// Construct an NSDate whose hour is set to the specified hour, with minutes and seconds 0.
// (The date of the object is irrelevant, we won't use it.)
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hour];
[components setMinute:0];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *topOfHour = [calendar dateFromComponents:components];

// Get a localized string representation of the time, e.g. "5:00 PM" or "17:00"
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
timeFormatter.timeStyle = NSDateFormatterShortStyle;
timeFormatter.dateStyle = NSDateFormatterNoStyle;
NSString *hourString = [timeFormatter stringFromDate:topOfHour];

// Remove the ":00" from the string.
hourString = [hourString stringByReplacingOccurrencesOfString:@":00" withString:@""];

如果您只想从包含 AM/PM 指示符的时间字符串中删除“:00”部分,以得到像(例如)“5 PM”或“17:00”这样的字符串,您可以将其换行上面的最后一行是有条件的,例如:

if ([hourString containsString:timeFormatter.AMSymbol] || [hourString containsString:timeFormatter.PMSymbol])
{
hourString = [hourString stringByReplacingOccurrencesOfString:@":00" withString:@""];
}

由于此实现依赖于硬编码的“:00”,因此它可能不适用于某些语言环境,例如不使用 : 作为小时-分钟分隔符的语言环境,或不从 0 开始计算分钟的语言环境,或还在 NSDateFormatterShortStyle 中包含秒的语言环境.

关于iOS:从 NSDate 获取本地化时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30616185/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com