NEW: Learn to build the incredible iOS 15 Weather app today! >>

Question about Unix time to NSDate conversion?

Forums > SwiftUI

Can someone explain to me why the following code shows a "Normal" date format but when you print it theres another format? This is just a playground code test.

date shows "Jan 11, 2022 at 7:35 AM"

but prints "2022-01-11 13:35:33 +0000\n"

I'm assuming thats perhaps UTC time?

And it needs further conversion?

import UIKit
import SwiftUI

let unixTime = 1641908133

var date = NSDate(timeIntervalSince1970: TimeInterval(unixTime))

print(date)

   

To answer my own question this code below converts the time to local time:

import UIKit
import SwiftUI
import Foundation

let unixTime = 1641908133

var date = NSDate(timeIntervalSince1970: TimeInterval(unixTime))
let utcDateFormatter = DateFormatter()
utcDateFormatter.dateStyle = .short
utcDateFormatter.timeStyle = .short

let date1 = date
print(utcDateFormatter.string(from: date1 as Date))

   

Can I ask what time zone you are located in, working on an app based on timing, and testing in different timezones seems....difficult.

I believe your first time is UTC time as you suggest, and the second actually formats it for where you are located.

   

I'm located Central Timezone in US.

1      

Hacking with Swift is sponsored by Sentry

SPONSORED With Sentry’s error and performance monitoring for iOS, you see mobile vitals that actually matter, can solve any latency issues quickly, and learn how each release is performing over time.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.