Luke97
Luke97

Reputation: 539

How to save the current date to CoreData?

I have an attribute in CoreData which accepts a date value. I just want to get the current date and save it in this format "dd/mm/yyyy" . But don't know how. Thanks

Upvotes: 5

Views: 14343

Answers (3)

Rajat Jain
Rajat Jain

Reputation: 1022

To save dates in Core Data I have created the following extension

 extension Date {
     /**
      Formats a Date

      - parameters format: (String) for eg dd-MM-yyyy hh-mm-ss
      */
     func format(format:String = "dd-MM-yyyy hh-mm-ss") -> Date {
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = format
         let dateString = dateFormatter.string(from: self)
         if let newDate = dateFormatter.date(from: dateString) {
             return newDate
         } else {
             return self
         }
     }
 }

To set a date value of a field

 let date = Date()
 entity?.setValue(date.format(), forKey: "updated_at")

Note: You may see date saved as timestamp when you open your database. Please refer to the following issue NSDate being saved as timestamp in CoreData

You can also pass you own date formats in the "format()" extension to get different types of dates in the application

Upvotes: 0

Rocky Balboa
Rocky Balboa

Reputation: 814

Here you can store date in coreData as shown in format

let date = NSDate()
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
var dateString = dateFormatter.string(from: date as Date)

store dateString in your coreData

Upvotes: 3

Russell
Russell

Reputation: 5554

If you're storing it as Date, then you have no control over the format until you try to present the returned value somewhere, and you just store Date()

If you're storing it as shown, then you need to use a DateFormatter to create the string you need

Upvotes: 6

Related Questions