I'm trying to extract month array from Gregorian Calendar. Extracting weekday is easily done by following method.
public static func getWeekDay(_ dayIndex: Int) -> String {
Calendar(identifier: .gregorian).weekdaySymbols[dayIndex]
} // dayIndex 0 will return Sun
But this time I want to do the same for Month. I'm expecting an array like this ["Jan", "Feb", "Mar", .... "Dec"]
. But all I got is "M01"
, "M02"
.... etc.
po Calendar(identifier: .gregorian).monthSymbols
▿ 12 elements
- 0 : "M01"
- 1 : "M02"
- 2 : "M03"
- 3 : "M04"
- 4 : "M05"
- 5 : "M06"
- 6 : "M07"
- 7 : "M08"
- 8 : "M09"
- 9 : "M10"
- 10 : "M11"
- 11 : "M12"
It goes the same for standaloneMonthSymbols
and shortMonthSymbols
.
And veryShortStandaloneMonthSymbols
returns ["1", "2", "3", "4" ..., "12].
Any Idea for ["Jan", "Feb", "Dec"]?
CodePudding user response:
monthSymbols
will return a list of months in the calendar, localized to the Calendar’s locale. By default, Calendars have no locale set. If you wish to receive a localized answer, be sure to set the locale.
public func getMonths() -> [String] {
var cal = Calendar(identifier: .gregorian)
cal.locale = Locale(identifier: "en_US_POSIX")
return cal.monthSymbols
}
print(getMonths()) // -> ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
If u want short month symbols use return cal.shortMonthSymbols
.
Update :
If you use Locale(identifier: "en_US_POSIX")
it will always return the result in a English as mentioned above. Using Locale.current
instead of that will return a localized output for users depend on where they are.
eg : Assume a scenario where Lacale.current = Locale(identifier: "fr_FR")
, then the result would be -> ["janvier", "février", "mars", "avril", "mai", .......