NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

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



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.


Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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.