user1960169
user1960169

Reputation: 3663

How to get local time zone date in swift 3

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?

Upvotes: 7

Views: 13395

Answers (3)

awex
awex

Reputation: 159

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()

Upvotes: 1

Efren
Efren

Reputation: 4907

As per the documentation:

If you want “date information in a given time zone” in order to display it, you should use DateFormatter to format the date.

eg:

// If date is "Dec 7, 2018 at 6:34 AM" UTC
let today=Date() // is always UTC
var calendar = Calendar.current
calendar.timeZone = .current
let components = calendar.dateComponents([.year, .month, .day], from: today)
let day = components.day  // Is 7
// To print with local version
let myFormatter = DateFormatter()
myFormatter.timeZone = TimeZone(secondsFromGMT: 3600*10)
myFormatter.dateFormat = "dd"
print(myFormatter.string(from: today))  // prints "07\n"
myFormatter.timeZone = TimeZone(secondsFromGMT: -3600*11)
print(myFormatter.string(from: today))  // prints "06\n"

Upvotes: 0

Krunal
Krunal

Reputation: 79776

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)

Upvotes: 6

Related Questions