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

// in Detail View
let dateFormatter = DateFormatter()

//much further down...

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


thanks for any tips, Bill



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,



Thank you @delawaremathguy ! That fixed it.


Hacking with Swift is sponsored by Superwall

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

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.