0

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.

Owen K
  • 11
  • 1
  • 2
    `2022-03-31 23:00:00 +0000` ***is*** `00:00 2022-04-01` in your timezone (the UK, I'm guessing?). Please see https://stackoverflow.com/questions/39937019/nsdate-or-date-shows-the-wrong-time – Sweeper Feb 18 '22 at 17:10

1 Answers1

0

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

Owen K
  • 11
  • 1