Set current time to yyyy-MM-dd 00:00:00 using Swift

后端 未结 3 780
广开言路
广开言路 2021-01-25 02:25

I want to ask about NSDate, how to set/format current time like \"2015-08-12 09:30:41 +0000\" to \"2015-08-12 00:00:00 +0000

I\'m already using :

         


        
3条回答
  •  情话喂你
    2021-01-25 02:50

    let dateString = "2015-08-12 09:30:41 +0000"
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
    dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
    if let dateFromString = dateFormatter.dateFromString(dateString.componentsSeparatedByString(" ").first ?? "") {
        println(dateFromString)  // "2015-08-12 00:00:00 +0000"
    }
    

    Swift 4

    let dateString = "2019-05-04 09:30:41 +0000"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    if let dateFromString = dateFormatter.date(from: dateString.components(separatedBy: " ").first ?? "") {
        print(dateFromString)  // "2019-05-04 00:00:00 +0000"
    }
    

提交回复
热议问题