简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM