1

I have displayed the list of timezones in my app. If user selects a particular timezones, I need to change the local timezone to the selected timezone by the user.

let region = Region(tz: timeZoneName.timeZone  , cal: cal, loc: cal.locale!)
let date = Date().inRegion(region: region).absoluteDate

Here is the problem, the region is changed to the selected timezone but the date issuing the local timezone.

Khadija
  • 310
  • 1
  • 9
sathish
  • 571
  • 1
  • 5
  • 16

2 Answers2

2

A Date contains no timezone. From apple's docs: A specific point in time, independent of any calendar or time zone.

The timezone comes into play as soon as you want to present a date to the user. And that's what a DateFormatter is for. As @AlexWoe89 already pointed out, it let's you convert a string, containing a date into a Date object, but also lets you convert a given date into a string representing the date in the time zone you set to the timeZone property of DateFormatter.

let date = Date()

var dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"

dateFormatter.timeZone = TimeZone(identifier: "America/Los_Angeles")
let dateString1 = dateFormatter.string(from: date)

dateFormatter.timeZone = TimeZone(identifier: "Germany/Berlin")
let dateString2 = dateFormatter.string(from: date)

This will store 2017-10-23 04:27 in dateString1, while the same date leads to 2017-10-23 13:27 in dateString2.

D. Mika
  • 2,577
  • 1
  • 13
  • 29
  • Hi, How to convert the DateInRegion to Date @D. Mika – sathish Oct 23 '17 at 14:18
  • By calling .absoluteDate. But I don't know very much about SwiftDate library, to be honest. But I guess DateInRegion has a way to get a String from it's containing date, without using absoluteDate and a DateFormatter. – D. Mika Oct 23 '17 at 14:39
  • Thank you @D. Mika – sathish Oct 24 '17 at 14:46
  • Here, I want to get the output as Date format instead of String. How should I get in Date? @D. Mika – sathish Oct 24 '17 at 14:49
0

You can use DateFormatter as a solution, try something like this:

let dateString = "<yourDateAsString>"

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // => there are a lot of identifiers you can use
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
dateFormatter.defaultDate = Date()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm” // => your needed time format

let convertedDate = dateFormatter.date(from: dateString) 
AlexWoe89
  • 844
  • 1
  • 11
  • 23