Format a date within a struct

Hi, I have a struct for a model I am using called Event and in that model I have a date which is saved in the universal date format of Y-m-d.

Here is the struct I have:

struct Event: Codable, Identifiable {

    var id:Int = 0
    var name:String = ""
    var date:String = ""
    
}

I want to format the date into a jS F Y format when it's printed on the screen but I'm not sure if or how I can essentially format this date before I come to use it in my view.

Is there a way to filter this data before it gets to the view where it's used or would I have to format the date elsewhere?

I have tried to add a function below the struct but it seems that the Event from within my function is undefined / not in scope.

Something very similar was discussed recently, should get you started.

Thank you for linking to that, I'll look into it further.

You can define your function within the struct not outside it that will solve your "not in scope issue". The other mechanism you might want to use it a "computed property" like

var dateFormat: String {
// date logic goes in here
return ""
}

In this case you might want to then consider making your internal date "private", and using the computed property in your view.

You might also want to consider storing your date as an actual swift Date;

var myDate: Date

and using the very rich formatting and date management routines built into swift. See Paul Hudsons videos on Date Formatting....

Here is the link: Working with dates - a free Hacking with iOS: SwiftUI Edition tutorial

1 Like