0

I have an issue with TimeZone. I want get current time in my local, but I get wrong one. I set the time zone to TimeZone(identifier: "Asia/Baku")!, but it's not working. it show me the time 11:25, but current time in my desktop and localized country is 15:25. this is my simple code:

let date = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone(identifier: "Asia/Baku")!
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let currentDate = calendar.date(from: components)
print("Current Date: \(currentDate!)")
Jack Daniel
  • 2,397
  • 8
  • 33
  • 58
  • 3
    Is the output something like `2017-08-25 11:40:14 +0000`? – Printing a Date *always uses UTC* (indicated by the +0000). – Martin R Aug 25 '17 at 11:40
  • @MartinR yes, exactly. How I can set the correct time? I know in our region UTC must be +4 – Jack Daniel Aug 25 '17 at 11:43
  • 1
    A Date is an absolute point in time and has to timezone. To display a date according you locale, use a DateFormatter. – Martin R Aug 25 '17 at 11:45
  • @MartinR oh, I noticed you mark question as duplicate. I will check the solution from pointed post. thank you – Jack Daniel Aug 25 '17 at 11:47
  • 2
    Actually this is asked regularly. If you search for "nsdate wrong by some hours" or "nsdateformatter wrong hour" then you'll find many similar questions with answers. – Martin R Aug 25 '17 at 11:49

0 Answers0