-1

I have a time zone as String type and I would like to get date (with format dd:mm:yyyy) and time (with format hh:mm:ss) in this timezone in Swift 4. How could i do this?

I've seen Calendar library but I don't understand how to see it to resolve my problem.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • 2
    By the way, while Marcel shows you how to set `dateFormat` to achieve what you want, you should ask yourself what the purpose of the resulting string is. For example, if it's for exchanging with a web service or saving in a database, you'd set `dateFormat`, but also specify `locale` of `en_US_POSIX` and `timeZone` of UTC. But if it's for showing in UI, you shouldn't use `dateFormat` at all, and you should instead use `dateStyle` and `timeStyle`, so the date and time are shown in the user's preferred format, not yours. E.g. So US users see Oct 28, 2017, but UK users see 28 Oct 2017. – Rob Oct 28 '17 at 20:10
  • https://stackoverflow.com/a/28347285/2303865 – Leo Dabus Oct 28 '17 at 21:06

1 Answers1

6
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd:MM:yyy hh:mm:ss"

let timeZone = TimeZone(identifier: "Europe/Amsterdam")

dateFormatter.timeZone = timeZone

dateFormatter.string(from: Date())

Although, I think the format "dd-MM-yyyy HH:mm:ss" seems more correct. Having said that; setting dateFormat should be used for setting the format when parsing a custom date format. When you are formatting a date to show to the user, you should use a date format that the user expects (in the default system locale). To do that you should use dateStyle and timeStyle:

dateFormatter.dateStyle = .medium
print(dateFormatter.string(from: Date())) // prints "Oct 28, 2017"

dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .medium
print(dateFormatter.string(from: Date())) // prints "Oct 28, 2017 Oct 28, 2017 at 11:19:13 PM"
Marcel
  • 6,393
  • 1
  • 30
  • 44