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      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.