swiftnsdateformatternsdatepicker

How to persist and load NSDatePicker date values


I am very new to MacOs development so apologies if this is a simplistic question:

I have an app that stores and loads data to an SQlite db.

A view has an NSDatePicker in graphic mode and the view can be either in 'add' or 'edit' mode ie adding or retrieving and updating data from SQlite

Another view has an NSTableView where one of the columns is the date that I want to load from SQlite into the column.

My question is what property of the datePicker should I persist - datePicker.stringValue or datepicker.dateValue?

If it is .stringValue can I simply load this when displaying the datePicker on the 'edit' view?

If it is .dateValue how do I get the value for the tableView? (use NSDateFormatter?)

SQlite does not have a date type so I am using a text field to store the date


Solution

  • Converting dates back and forth to string is messy and somewhat fragile. I suggest saving it as a floating point value instead.

    To convert a date to a Double use:

    let interval = aDate.timeIntervalSinceReferenceDate
    

    (Where aDate is a Date object, and interval is a Double, a.k.a a TimeInterval)

    Conversely, to convert a floating point value back to a Date:

    let aDate = Date(timeIntervalSinceReferenceDate: interval)
    

    You should be able to save the resulting interval floating-point value to your SQL database. Use Double precision for the floating point value.