How can I convert string date to NSDate?

2019-01-01 06:22发布

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

16条回答
素衣白纱
2楼-- · 2019-01-01 07:01

try this:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /* find out and place date format from 
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
let date = dateFormatter.dateFromString(/* your_date_string */)

For further query, check NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.

Swift 3 and later (Swift 4 included)

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = /* date_format_you_want_in_string from
                            * http://userguide.icu-project.org/formatparse/datetime
                            */
guard let date = dateFormatter.date(from: /* your_date_string */) else {
   fatalError("ERROR: Date conversion failed due to mismatched format.")
}

// use date constant here
查看更多
春风洒进眼中
3楼-- · 2019-01-01 07:02

To add String within Date Format in Swift, I did this

 var dataFormatter:NSDateFormatter = NSDateFormatter()
                dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)
查看更多
刘海飞了
4楼-- · 2019-01-01 07:03

Details

Swift 4, xCode 9.2 / Swift 3, xCode 8.2.1

Date format extensions

import Foundation

extension DateFormatter {

    convenience init (format: String) {
        self.init()
        dateFormat = format
        locale = Locale.current
    }
}

extension String {

    func toDate (format: String) -> Date? {
        return DateFormatter(format: format).date(from: self)
    }

    func toDateString (inputFormat: String, outputFormat:String) -> String? {
        if let date = toDate(format: inputFormat) {
             return DateFormatter(format: outputFormat).string(from: date)
        }
        return nil
    }
}

extension Date {

    func toString (format:String) -> String? {
        return DateFormatter(format: format).string(from: self)
    }
}

Usage

var dateString = "14.01.2017T14:54:00"
let format = "dd.MM.yyyy'T'HH:mm:ss"
let date = Date()

print("original String with date:               \(dateString)")
print("date String() to Date():                 \(dateString.toDate(format: format)!)")
print("date String() to formated date String(): \(dateString.toDateString(inputFormat: format, outputFormat: "dd MMMM")!)")
print("format Date():                           \(date.toString(format: "dd MMM HH:mm")!)")

Result

enter image description here

More information

About date format

查看更多
回忆,回不去的记忆
5楼-- · 2019-01-01 07:03

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.

查看更多
其实,你不懂
6楼-- · 2019-01-01 07:03

Since Swift 3, many of the NS prefixes have been dropped.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" 
/* date format string rules
 * http://userguide.icu-project.org/formatparse/datetime
 */

let date = dateFormatter.date(from: dateString)
查看更多
心情的温度
7楼-- · 2019-01-01 07:04

Below are some string to date format converting options can be usedin swift iOS.

  1. Thursday, Dec 27, 2018 format= EEEE, MMM d, yyyy
  2. 12/27/2018 format= MM/dd/yyyy
  3. 12-27-2018 09:59 format= MM-dd-yyyy HH:mm
  4. Dec 27, 9:59 AM format= MMM d, h:mm a
  5. December 2018 format= MMMM yyyy
  6. Dec 27, 2018 format= MMM d, yyyy
  7. Thu, 27 Dec 2018 09:59:19 +0000 format= E, d MMM yyyy HH:mm:ss Z
  8. 2018-12-27T09:59:19+0000 format= yyyy-MM-dd'T'HH:mm:ssZ
  9. 27.12.18 format= dd.MM.yy
  10. 09:59:19.815 format= HH:mm:ss.SSS
查看更多
登录 后发表回答