How can I convert string date to NSDate?

前端 未结 18 1683
花落未央
花落未央 2020-11-22 16:14

I want to convert \"2014-07-15 06:55:14.198000+00:00\" this string date to NSDate in Swift.

相关标签:
18条回答
  • 2020-11-22 16:44
    import Foundation
    
    let now : String = "2014-07-16 03:03:34 PDT"
    var date : NSDate
    var dateFormatter : NSDateFormatter
    
    date = dateFormatter.dateFromString(now)
    
    date // $R6: __NSDate = 2014-07-16 03:03:34 PDT
    

    https://developer.apple.com/library/prerelease/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/index.html#//apple_ref/doc/uid/20000447-SW32

    0 讨论(0)
  • Swift 3,4:

    2 useful conversions:

    string(from: Date) // to convert from Date to a String
    date(from: String) // to convert from String to Date
    

    Usage: 1.

    let date = Date() //gives today's date
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd.MM.yyyy"
    let todaysDateInUKFormat = dateFormatter.string(from: date)
    

    2.

     let someDateInString = "23.06.2017"
     var getDateFromString = dateFormatter.date(from: someDateInString)
    
    0 讨论(0)
  • 2020-11-22 16:49

    FOR SWIFT 3.1

    func convertDateStringToDate(longDate: String) -> String{
    
        /* INPUT: longDate = "2017-01-27T05:00:00.000Z"
         * OUTPUT: "1/26/17"
         * date_format_you_want_in_string from
         * http://userguide.icu-project.org/formatparse/datetime
         */
    
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let date = dateFormatter.date(from: longDate)
    
        if date != nil {
    
            let formatter = DateFormatter()
            formatter.dateStyle = .short
            let dateShort = formatter.string(from: date!)
    
            return dateShort
    
        } else {
    
            return longDate
    
        }
    }
    

    NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR

    0 讨论(0)
  • 2020-11-22 16:50

    This work for me..

        import Foundation
        import UIKit
    
        //dateString = "01/07/2017"
        private func parseDate(_ dateStr: String) -> String {
                let simpleDateFormat = DateFormatter()
                simpleDateFormat.dateFormat = "dd/MM/yyyy" //format our date String
                let dateFormat = DateFormatter()
                dateFormat.dateFormat = "dd 'de' MMMM 'de' yyyy" //format return
    
                let date = simpleDateFormat.date(from: dateStr)
                return dateFormat.string(from: date!)
        }
    
    0 讨论(0)
  • 2020-11-22 16:51

    Details

    • Swift 4, Xcode 9.2
    • Swift 5, Xcode 10.2 (10E125)

    Solution

    import Foundation
    
    extension DateFormatter {
    
        convenience init (format: String) {
            self.init()
            dateFormat = format
            locale = Locale.current
        }
    }
    
    extension String {
    
        func toDate (dateFormatter: DateFormatter) -> Date? {
            return dateFormatter.date(from: self)
        }
    
        func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
            guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
            return DateFormatter(format: outputFormat).string(from: date)
        }
    }
    
    extension Date {
    
        func toString (dateFormatter: DateFormatter) -> String? {
            return dateFormatter.string(from: self)
        }
    }
    

    Usage

    var dateString = "14.01.2017T14:54:00"
    let dateFormatter = DateFormatter(format: "dd.MM.yyyy'T'HH:mm:ss")
    let date = Date()
    
    print("original String with date:               \(dateString)")
    print("date String() to Date():                 \(dateString.toDate(dateFormatter: dateFormatter)!)")
    print("date String() to formated date String(): \(dateString.toDateString(dateFormatter: dateFormatter, outputFormat: "dd MMMM")!)")
    let dateFormatter2 = DateFormatter(format: "dd MMM HH:mm")
    print("format Date():                           \(date.toString(dateFormatter: dateFormatter2)!)")
    

    Result

    More information

    About date format

    0 讨论(0)
  • 2020-11-22 16:52

    The code fragments on this QA page are "upside down"...

    The first thing Apple mentions is that you cache your formatter...

    Link to Apple doco stating exactly how to do this:

    Cache Formatters for Efficiency Creating a date formatter is not a cheap operation. ...cache a single instance...

    Use a global...

    let df : DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        return formatter 
    }()
    

    Then simply use that formatter anywhere...

    let s = df.string(from: someDate)
    

    or

    let d = df.date(from: someString)
    

    Or use any of the other many, many convenient methods on DateFormatter.

    It is that simple.

    (If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)

    Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.

    0 讨论(0)
提交回复
热议问题