You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何通过索引获取英文缩写月份数组?

解决Swift中获取英文月份缩写数组的问题

问题描述

之前通过以下代码能正常获取英文星期几:

public static func getWeekDay(_ dayIndex: Int) -> String {
    Calendar(identifier: .gregorian).weekdaySymbols[dayIndex]
} // dayIndex 0 will return Sun

但尝试获取月份数组时,无论是调用monthSymbols、shortMonthSymbols还是standaloneMonthSymbols,返回的都是["M01", "M02"....]这类格式,而非期望的["Jan", "Feb", ..., "Dec"];调用veryShortStandaloneMonthSymbols则返回["1", "2", ..., "12"]。

原因

你创建的Calendar实例默认使用当前系统的Locale,如果系统Locale不是英文,就会返回对应语言/地区的月份格式(比如你看到的M01是特定地区的月份编号格式)。要获取英文缩写,必须显式指定英文Locale。

解决方案

创建Calendar时,为其设置英文Locale(推荐用en_US_POSIX,它不受系统区域设置影响,适合编程场景),再调用对应的月份符号属性即可:

代码示例

// 创建指定英文Locale的公历实例
let gregorianCal = Calendar(identifier: .gregorian)
gregorianCal.locale = Locale(identifier: "en_US_POSIX")

// 获取短月份缩写数组 ["Jan", "Feb", ..., "Dec"]
let shortMonths = gregorianCal.shortMonthSymbols
print(shortMonths)

// 如果需要完整月份名称,用monthSymbols
let fullMonths = gregorianCal.monthSymbols
print(fullMonths) // ["January", "February", ..., "December"]

简化写法

也可以直接在初始化时传入Locale:

let shortMonths = Calendar(identifier: .gregorian, locale: Locale(identifier: "en_US_POSIX")).shortMonthSymbols

内容的提问来源于stack exchange,提问作者Zin Win Htet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:55:16