dateFormatterPrint.dateFormat = "YYYY-MM-dd"
dateFormatterPrint.timeZone = TimeZone.current
dateFormatterPrint.string(from: date)
my date value is "2020-12-28 16:00:00" in date type. dateFormatterPrint.string(from: date) return "2021-12-29" instead of "2020-12-29".
How can solve it?
In my environment:
Code Block print(Locale.current) //->en_US (current) print(TimeZone.current) //->Asia/Tokyo (current) let date = Date() let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "YYYY-MM-dd" dateFormatterPrint.timeZone = TimeZone.current dateFormatterPrint.string(from: date) //->"2021-12-28"
This is the first week of the week-year 2021.
Fixed Formats
Try using yyyy instead of YYYY:year Y 1..n 1997 Year (in "Week of Year" based calendars). Normally the length specifies the padding, but for two letters it also specifies the maximum length. This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.
Code Block let date = Date() let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "yyyy-MM-dd" dateFormatterPrint.timeZone = TimeZone.current dateFormatterPrint.string(from: date) //->"2020-12-28"