-1

I live by end of month dates such as "2019-02-28 23:59:59"

print when I print out that date it tells me "Mar-2019". No it is still "Feb-2019"

print(dt1.toString(dateFormat: "MMM-YYYY")

I do use SwiftDate. I also get this issue with the DateFormatter().

so instead of clean code I end up having to subtracting a day to get the correct month-year to display.

Why?

diogenes
  • 1,865
  • 3
  • 24
  • 51

1 Answers1

3

You need to set Timezone & date format properly as below,

let string = "2019-02-28 23:59:59"
let df = DateFormatter()
df.timeZone = .current
df.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = df.date(from: string)
print(date?.description(with: .current)) //Thursday, February 28, 2019 at 11:59:59 PM Gulf Standard Time
df.dateFormat = "MMM-yyyy"
print(df.string(from: date!)) // Feb-2019
Kamran
  • 14,987
  • 4
  • 33
  • 51
  • I will suggest give it a read [Understanding Dates](http://www.maddysoft.com/articles/dates.html). – Kamran Oct 13 '19 at 11:45
  • I see what everyone is saying, thank you. I have been using SwiftDate because I thought is was simpler that using all the Calendar and DateFormatter() codes. Adding the locals and regions with SwiftDate offsets the simplicity I thought. I still am not sure which it the best approach? The apps will be international so that is another variable to consider. Anyone have thoughts on SwiftDate vs pure Swift? Cheers. – diogenes Oct 14 '19 at 01:07
  • @diogenes I think its a very helpful library and it saves time. But for better use, one should know the basic date functions. If you have read the above article i shared then it will help you a lot using this library. – Kamran Oct 14 '19 at 06:12