I am writing code to convert two dates from strings to date objects however this is not working as expected for some dates that I pass on to the date formatter.
Here is my code:
let stringDateMinimum = "00:00 " + year + "-0" + String(month+1) + "-01"
let stringDateMaximum = "00:00 " + year + "-0" + String(month+2) + "-01"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm yyyy/MM/dd"
let minimimDate = dateFormatter.date(from: stringDateMinimum)
let maximumDate = dateFormatter.date(from: stringDateMaximum)
print(stringDateMinimum)
print(minimimDate ?? "")
print(stringDateMaximum)
print(maximumDate ?? "")
This is the output from in the console:
00:00 2022-03-01
2022-03-01 00:00:00 +0000
00:00 2022-04-01
2022-03-31 23:00:00 +0000
If you compare lines 3 and 4 in the console, you can see that the string inputted into the date formatter does not match the output of the date formatter when it should.
Thank you to Sweeper for your comment. The answer was to include a time zone in the string I was inputting into the date formatter. So for example I changed the date format to:
dateFormatter.dateFormat = "HH:mm yyyy/MM/dd Z"
and added +0000 for my timezone to the stringDateMinimum and stringDateMaximum
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.