DateFormatter().string(from: ) return "2021-Dec" instead of "2020-Dec"

let dateFormatterPrint = DateFormatter()
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?
Answered by OOPer in 654413022
You should better show how you get date, and your current locale and timezone.

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

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.

Try using yyyy instead of YYYY:
Code Block
let date = Date()
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
dateFormatterPrint.timeZone = TimeZone.current
dateFormatterPrint.string(from: date) //->"2020-12-28"


Accepted Answer
You should better show how you get date, and your current locale and timezone.

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

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.

Try using yyyy instead of YYYY:
Code Block
let date = Date()
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "yyyy-MM-dd"
dateFormatterPrint.timeZone = TimeZone.current
dateFormatterPrint.string(from: date) //->"2020-12-28"


DateFormatter().string(from: ) return "2021-Dec" instead of "2020-Dec"
 
 
Q