Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get local time zone date in swift 3

Tags:

date

ios

swift3

I am getting year,month and day from a given date in this way.

let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)    

let day=components.day

But I'm getting one day ahead from my current day. How can I solve this?

like image 250
user1960169 Avatar asked Jun 20 '17 10:06

user1960169


People also ask

How do you convert UTC to local time in Swift?

isTimeFromServer { dateFormatter. dateFormat = "H:mm" dateFormatter. timeZone = TimeZone(abbreviation: "UTC") dateFormatter. string(from: date!) }

How do you convert UTC time to local time?

Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.


2 Answers

let date = Date().description(with: Locale.current)
print("date ---> \(date)")

Result: date ---> Tuesday, June 20, 2017 at 4:35:15 PM India Standard Time

I'm getting perfect system/local time.

You code is working,

let today=Date()
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: today)

let day = components.day
let hour = components.hour
let minute = components.minute
print("day = \(day)\nhour = \(hour)\nminute = \(minute)")

Result:
day = Optional(20)
hour = Optional(16)
minute = Optional(35)

like image 139
Krunal Avatar answered Oct 17 '22 05:10

Krunal


Get Local Date and Time

Swift 5:

let today = Date()
let timeZone = Double(TimeZone.current.secondsFromGMT(for: today))
let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZone), to: today) ?? Date()
like image 22
awex Avatar answered Oct 17 '22 04:10

awex