Kay Weng
Kay Weng

Reputation: 73

Get Local time zone date by date component

Ok, this is my codes for format the current date to GMT format and return the value in date type. I 'po' the nowComponent variable while debugging which shows me the current local time zone values but the block of code 'calendar.date(from: nowComponents)!' still return me a UTC date. How to get the Date in local timezone ?

    var nowComponents = DateComponents()
    let date = Date()

    nowComponents.year = (calendar as NSCalendar).component(NSCalendar.Unit.year, from: date)
    nowComponents.month = (calendar as NSCalendar).component(NSCalendar.Unit.month, from: date)
    nowComponents.day = (calendar as NSCalendar).component(NSCalendar.Unit.day, from: date)
    nowComponents.hour = (calendar as NSCalendar).component(NSCalendar.Unit.hour, from: date)
    nowComponents.minute = (calendar as NSCalendar).component(NSCalendar.Unit.minute, from: date)
    nowComponents.second = (calendar as NSCalendar).component(NSCalendar.Unit.second, from: date)

    (nowComponents as NSDateComponents).timeZone = TimeZone.current

    return calendar.date(from: nowComponents)!

Upvotes: 1

Views: 455

Answers (1)

rmaddy
rmaddy

Reputation: 318934

None of your code is necessary. The line:

let date = Date()

is all you need. This gives you the current date and time.

Your mistake is using po to print the date. This uses the description method on the date which shows the debug output of the date and that output shows the date in UTC time.

If you want to see the date, as a string, in local time, use DateFormatter:

let df = DateFormatter()
df.dateStyle = .long
df.timeStyle = .long
let str = df.string(from: date)
print(str)

This will show the date in local time.

Upvotes: 2

Related Questions