如何将日期重新格式化为只有年月日? Swift

How to reformat a Date to only Year Month and Day? Swift

我无法重新设置日期格式以仅显示 .year .month.day。输出打印与我输入的字符串相同,但 hourminutes 显示为零,我的目标是只有一个字符串 "yyyy-MM-dd",因为我将使用它来获取 CoreData 备案。如果我使用那个日期格式 Xcode 崩溃,因为传入的日期格式是 "yyyy-MM-dd HH:mm:ssZZZZ"。我遵循了 建议的解决方案,但在某些情况下无法正常工作。如何重新格式化日期? 一如既往地非常感谢你。 这是函数:

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)" )
        }
    }
func getDateWithoutTime(string: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
    if let date = dateFormatter.date(from: string) {
        dateFormatter.dateFormat = "yyyy-MM-dd"
        return dateFormatter.string(from: date)
    }
    return nil
}
print(getDateWithoutTime1(string:"2019-05-13 12:27:53GMT"))   

2019-05-13

只需创建一个String扩展

1.String 转换为 Date,格式为 yyyy-MM-dd HH:mm:ssZZZZ

2.Date 转换为 String,格式为 yyyy-MM-dd

extension String {
    var formattedDate: String? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZZZZ"
        if let date = dateFormatter.date(from: self) {
            print(date)
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return dateFormatter.string(from: date)
        }
        return nil
    }
}

示例:

let dateStr = "2017-04-10 10:33:42GMT"
let formattedDate = dateStr.formattedDate //Output: "2017-04-10"

使用下面的函数传递日期、当前日期格式和所需的日期格式。

let dateStr = self.convertDateFormaterCommon(currentFormat: "yyyy-MM-dd HH:mm:ss", reqdFormat: "dd MMM, yyyy", dateStr: myObj.transferDate ?? "")

func convertDateFormaterCommon(currentFormat:String, reqdFormat:String, dateStr: String) -> String
{
    if dateStr != ""{
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = currentFormat
        dateFormatter.locale = Locale(identifier: "en_US")
        let date = dateFormatter.date(from: dateStr)
        dateFormatter.dateFormat = reqdFormat
        return  dateFormatter.string(from: date ?? Date())
    }
    return ""
}