Home > Back-end >  How can I convert date string to time string?
How can I convert date string to time string?

Time:06-30

I have a string that looks like this:

"date": "2022-06-30T02:15:00.000 07:00"

And I formatted it to convert to "HH:mm" like this:

func formatTime(string: String) -> String {
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "HH:mm"

    let date: Date? = dateFormatterGet.date(from: string)
    return dateFormatterPrint.string(from: date ?? Date())
}

The result I want it returns is 09:15, but it returns 02:15. Can someone tell me where I went wrong? Thank you

CodePudding user response:

"2022-06-30T02:15:00.000 07:00" is the date in the time zone plus 7 hours from the UTC time zone. Than this date in UTC is “ 2022-06-29T19:15:00Z”

while dateFormatterPrint has a default locale configuration according to the phone settings

You need to set UTC timezone

CodePudding user response:

In this case you might want to convert the DateTime to your local time first:

Convert To LocalTime:

func utcToLocal(dateStr: String) -> String? {
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "HH:mm"
  dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
  if let date = dateFormatter.date(from: dateStr) {
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "HH:mm"

    return dateFormatter.string(from: date)
  }
  return nil
}

And then:

let utcTime = formatTime(string: "2022-06-30T02:15:00.000 07:00")
let localTime = utcToLocal(dateStr: utcTime)
print(localTime)

The Result:

09:15

I hope this help you solve your problem.

  • Related