0

Essentially I would like to convert the following:

2022-07-01 14:35:00

To simply:

July 1st

The following is what I currently have because the initial input is string, but when I'm converting from string to date time the hour seems to have +2 hours added to it. Why is this happening?

// Create String
let string = "2022-07-01 14:35:00"


// Create Date Formatter
let dateFormatter = DateFormatter()

// Set Date Format
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

// Convert String to Date
let newdate = dateFormatter.date(from: string)
print(newdate!)
John
  • 965
  • 8
  • 16
  • `Date` in of itself does not have a "format" (it has a `description` which should really only be used for debugging/logging). Instead, you take your `newDate` and use another `DateFormatter` to generate a `String` representation of the date in the desired format – MadProgrammer Aug 02 '22 at 23:50
  • As a side note, I don't think `DateFormatter` can be configured to display `st`, `nd`, `rd` etc ... it would be a localisation nightmare, although you can manually do it if you want [for example](https://stackoverflow.com/questions/35700281/date-format-in-swift) – MadProgrammer Aug 02 '22 at 23:54
  • time depends on where you are. So in this case the +2 hours, may be due to the difference in `TimeZone`. So adjust the `TimeZone` in the format to match the original place, or put everything in `GMT` zone, or a common zone. – workingdog support Ukraine Aug 02 '22 at 23:57

1 Answers1

1

Time depends on where you are. So in this case the +2 hours you see, may be due to the difference in TimeZone. So adjust the TimeZone in the format to match the original place, or put everything in GMT TimeZone, or a common TimeZone of your choosing. Alternatively, keep the time difference.

Try something like this:

let string = "2022-07-01 14:35:00"

let readFormatter = DateFormatter()
readFormatter.timeZone = TimeZone(abbreviation: "GMT") // <-- here adjust
readFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let writeFormatter = DateFormatter()
writeFormatter.timeZone = TimeZone(abbreviation: "GMT") // <-- here adjust
writeFormatter.dateFormat = "LLLL dd"

if let theDate = readFormatter.date(from: string) {
    print("\n----> theDate: \(theDate)") // ----> theDate: 2022-07-01 14:35:00 +0000
    let simpleDate = writeFormatter.string(from: theDate)
    print("\n----> simpleDate: \(simpleDate)") // ----> simpleDate: July 01
}