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

SOLVED: Bookworm challenge - Date() not working

Forums > 100 Days of SwiftUI

Hi all, I'm a bit stuck on the Date challenge of the Bookworm project. So far, the dates don't display. I also tried finding the sqlite db file that was created in order to open with DB Browser for SQLite to see if the date is being stored correctly, but I can't find the actual DB file either.

All other details are displaying correctly. Has anyone solved this part?

I added to my Entity Attribute: date Type: Date

//relevant save section. 
Section {
                    Button("Save") {
                        // add the book
                        let newBook = Book(context: self.moc)
                        newBook.title = self.title
                        newBook.author = self.author
                        newBook.rating = Int16(self.rating)
                        newBook.genre = self.genre
                        newBook.review = self.review
                        newBook.date = Date()

                        try? self.moc.save()
                        self.presentationMode.wrappedValue.dismiss()
                    }//button

                }//section
// in Detail View
let dateFormatter = DateFormatter()

//much further down...

Text(dateFormatter.string(from: self.displayedBook.date ?? Date()))

https://github.com/BillMoriarty/Bookworm

thanks for any tips, Bill

3      

hi,

because you are calling the class DateFormatter, the default style and date format descriptors basically default in such a way that the return result is an empty string.

instead, give yourself a function (e.g., at the top of your DetailView) with a dateFormatter object and set its descriptors like this:

func dateRepresentation(for date: Date?) -> String {
    guard let date = date else { return "Date Unavailable" }
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long // <-- this is what's missing
    return dateFormatter.string(from: date)
}

then display it in your View with

Text(dateRepresentation(for: self.displayedBook.date))

hope that helps,

DMG

3      

Thank you @delawaremathguy ! That fixed it.

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.