Reputation: 25
I am using UITextField
date picker to save date in Core Data
.
On date picker sender i got the date in this format: 2017-04-02 14:56:41
.
I want to convert it to this format 02 April 2017
.
How can i do it? Below is my code:
var scheduledPickDate: NSDate!
@IBAction func scheduleDateTextFieldBeginEditing(_ sender: UITextField) {
let datePickerView:UIDatePicker = UIDatePicker()
datePickerView.minimumDate = NSDate() as Date
datePickerView.datePickerMode = UIDatePickerMode.date
sender.inputView = datePickerView
datePickerView.addTarget(self, action: #selector(WalkIn.ScheduledDateChanged), for: UIControlEvents.valueChanged)
}
func ScheduledDateChanged(sender:UIDatePicker){
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateFormat = "dd MMMM yyyy"
//print(sender.date)
scheduledPickDate = scheduledPickDate as NSDate!
//print(scheduledPickDate)
scheduledDateWalkinPatient.text = dateFormatter.string(from: sender.date)
}
// on save function
managedObj.setValue(scheduledPickDate, forKey: "dateSchedule") // 2017-04-02 14:56:41
How can I convert var scheduledPickDate
into this format 02 April 2017
?
Upvotes: 0
Views: 366
Reputation: 1996
In core data you should store your scheduledDate
as an NSDate
type entity.
when you retrieve that date, you can use your dateFormatter
. However, I would suggest using the .longStyle as dateFormat instead of "dd MMMM yyyy". It is way better for localization.
Upvotes: 0
Reputation: 485
You're already formatting the date with:
dateFormatter.string(from: sender.date)
You just can't store in Coredata a date in the format you want (unless you're using a String as attribute). If then you need to retrieve that date and show it to the user, you need to format it again
Upvotes: 1