I'm having trouble reformatting a date to only show .year
.month
and .day
. The output prints are the same string I input but with hour
and minutes
showing zeros and my goal is to only have a string "yyyy-MM-dd"
as i'l use it to fetch CoreData
for records. If I use that date format Xcode crashes because the incoming date format is "yyyy-MM-dd HH:mm:ssZZZZ"
. I followed suggested solution from Convert string to date in Swift but is not working in may case. How can a reformat the date?
As always thank you very much.
Here is the function :
func fetchBookings(date : String ) {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
// dateFormatter.dateFormat = "yyyy-MM-dd"
let dateFormatted = dateFormatter.date(from:date)!
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.year, .month,.day] , from: dateFormatted)
let dateToCheck = calendar.date(from: components)
let context = CoreData.databaseContext
let fetchRequest = NSFetchRequest<Booking>(entityName: "Booking")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "bookingDate", ascending: true)]
let userPredicate = NSPredicate(format: "user.name == %@", UserDetails.fullName ?? "")
let datePredicate = NSPredicate(format: "bookingDate CONTAINS %@", dateToCheck! as CVarArg)
let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [userPredicate, datePredicate])
fetchRequest.predicate = andPredicate
fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
do {
try fetchedResultController.performFetch()
print("##################### selectedDate in fetchBooking() is :\(self.selectedDate) ")
print(" bookings fetched")
print("booking date is: \(date)")
print("dateTocheck is: \(String(describing: dateToCheck!))")
print("today date is : \(Date())")
print("fetched objects are: \(String(describing: fetchedResultController.fetchedObjects))")
} catch {
print("Error fetching bookings :\(error)" )
}
}