简体   繁体   中英

Core Date date comparion from date picker text field

I am saving date in Core data successfully using Date type in model. Date saved in the format like 2017-04-02 14:56:41. When i retreive i want to filter date with current date text field which has a format like 02 April 2017. I am using predicate to compare both dates but app is crashed due to the difference or may be current date is in string.

let predicate = NSPredicate(format: "(dateSchedule >= %@ )", fromTextField.text!)

core data date: 2017-04-02 14:56:41 currentdate textfield date: 02 April 2017

Any help?

I'm assuming dateSchedule is a Date in coredata.

You can convert your text on a date variable (make sure the format is correct)

let dateString = "2017-04-02 14:56:41"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"

let dateObj = dateFormatter.date(from: dateString)

Then you create the predicate:

let predicate = NSPredicate(format: "(dateSchedule >= %@ )", dateObj)

EDIT:

If the time of the date is annoying you, you can use a utility like this one:

https://github.com/erica/SwiftDates

So you can filter with:

let predicate = NSPredicate(format: "(dateSchedule >= %@ )", dateObj.startOfDay)

In that way you are removing the time part and filtering by the beginning of the day

I would have formatted the dates this way:

let dateFormatter = Dateformatter()
dateFormatter.timeStyle = .none
dateFormatter.dateStyle = .medium

You can apply this to a date and get it as a string like this:

 whatever you are saving it as = dateFormatter.string(from: Date())

Then you will get a date like this, "Mar 17, 2017".

This way of using the date formatter is very practical in your very situation.

When you are fetching you just do it the same way:

 let predicate = NSPredicate(format: "(dateSchedule >= %@ )", fromTextField.text!)

but I would advise you to use a UIDatePickerView instead:

 let predicate = NSPredicate(format: "(dateSchedule >= %@ ), dateFormatter.string(from: datePickerView.date)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM