WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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)

1      

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

1      

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.

1      

I'm located Central Timezone in US.

2      

Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out 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.