日期选择器文本字段中的核心日期日期比较 [英] Core Date date comparion from date picker text field
问题描述
我使用模型中的日期类型成功地将日期保存在Core数据中。日期以2017-04-02 14:56:41这样的格式保存。当我检索时,我想用当前日期文本字段过滤日期,该字段的格式类似于2017年4月2日。我使用谓词比较两个日期,但由于差异导致应用程序崩溃,或者当前日期在字符串中。
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!)
核心数据日期:2017-04-02 14:56:41
currentdate文本字段日期:2017年4月2日
core data date: 2017-04-02 14:56:41 currentdate textfield date: 02 April 2017
有帮助吗?
推荐答案
我假设 dateSchedule 是coredata中的日期。
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)
然后您创建谓词:
let predicate = NSPredicate(format: "(dateSchedule >= %@ )", dateObj)
编辑:
如果日期时间很烦人,您可以使用像这样的实用程序:
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
这篇关于日期选择器文本字段中的核心日期日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!