UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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)

3      

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

3      

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.

3      

I'm located Central Timezone in US.

4      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.