1

What I want to do: Take the timestamp from my database and convert it to the timezone of the user.

My code:

let tryItNow = "\(model.timestampName)"
        
let format = DateFormatter()       
let date = format.date(from: tryItNow)       
format.timeZone = .current       
format.dateFormat = "yyyy-MM-dd HH:mm:ss Z"       
let dateString = format.string(from: date!)   //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
print(dateString)

The problem: I guess Xcode tells me, that date is empty, which can't really be true. I get the timestamp from a struct and this whole thing is in a function, that's why its called model.timestampName.

What I tried: Searching on the internet, here on stack overflow (most tutorials are 3 years old and I did not find anything for my specific case).

Jan Swoboda
  • 152
  • 2
  • 15

1 Answers1

1

You have to specify a format.dateFormat before converting your date:

let format = DateFormatter()      
format.dateFormat = "yyyy-MM-dd HH:mm:ss Z" // <- format of model.timestampName
let date = format.date(from: tryItNow)       
pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • Thanks for the fast reply, and yes this did solve one problem, but now I have another one. ```Unexpectedly found nil while unwrapping an Optional value```at the datestring – Jan Swoboda Jun 27 '20 at 12:02
  • I looked up how my timestamp (tryItNow) looks and Xcode tells me ``````. Do I have to change the code bcs of that? – Jan Swoboda Jun 27 '20 at 12:04
  • 1
    @JanSwoboda Please see [Convert Firebase Firestore Timestamp to Date (Swift)?](https://stackoverflow.com/questions/51116381/convert-firebase-firestore-timestamp-to-date-swift) – pawello2222 Jun 27 '20 at 12:06