Using a DateFormatter for this sort of thing is a really bad idea. See QA1480 NSDateFormatter and Internet Dates for an explanation as to why.
If you want to get the year, month and day from a date you should use calendar. For example:
import Foundation
func ymdForDate(_ date: Date) -> (year: Int, month: Int, day: Int) {
let c = Calendar(identifier: .gregorian)
let dc = c.dateComponents([.year, .month, .day], from: date)
return (dc.year!, dc.month!, dc.day!)
}
print(ymdForDate(Date()))
// prints: (year: 2020, month: 10, day: 1)
IMPORTANT I’m hard wiring the Gregorian calendar here. Do not use the default calendar (Calendar.current or Calendar.autoupdatingCurrent) for this because a non-Gregorian calendar can yield unexpected results. I gave a specific example of this in QA1480 but there are many more. For example, not all calendars have 12 months.
As to mapping that to a season, that’s a tricky problem, one that’s very dependent on the locale. For example:
-
Seasons are reversed in the southern hemisphere.
-
Locations near the equator don’t have seasons as they do in Europe. In some places there’s a wet season and dry season, and in others there’s simply no concept of seasons.
-
Even in places that do have seasons, the exact start and end dates vary (some folks consider them to change on the solstice and equinox, some folks consider them to change at the month boundaries).
It would be great if Foundation gave you an API to get season information but, AFAIK, it does not. A full solution to this problem will require a lot of work on your part.
it is summer in December in Japan
Ah, um, no its not. Japan is in the northern hemisphere and shares the same seasons as Europe (may be not the exact start and end dates but, as I mentioned above, those are subject to debate anyway). A better example would be where I grew up, Australia, where Christmas is indeed in summer.
Share and Enjoy
Quinn “The Eskimo!” @ DTS @ Apple