如何将字符串日期转换为NSDate?

时间:2014-07-16 09:44:54

标签: ios string swift nsdate

我想将“2014-07-15 06:55:14.198000 + 00:00”这个字符串日期转换为Swift中的NSDate。

18 个答案:

答案 0 :(得分:337)

试试这个:

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 */)

要进一步查询,请分别检查Objective-C和Swift的 Foundation 框架的NSDateFormatterDateFormatter类。

Swift 3及更高版本(包括Swift 4)

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

答案 1 :(得分:71)

Swift 4

import Foundation

let dateString = "2014-07-15" // change to your date format

var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date = dateFormatter.date(from: dateString)
println(date)

Swift 3

import Foundation

var dateString = "2014-07-15" // change to your date format

var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

var date = dateFormatter.dateFromString(dateString)
println(date)

我可以用这段代码来完成。

答案 2 :(得分:54)

 func convertDateFormatter(date: String) -> String
 {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let date = dateFormatter.dateFromString(date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC")
    let timeStamp = dateFormatter.stringFromDate(date!)


    return timeStamp
}

针对Swift 3进行了更新。

func convertDateFormatter(date: String) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let date = dateFormatter.date(from: date)


    dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm"///this is what you want to convert format
    dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
    let timeStamp = dateFormatter.string(from: date!)


    return timeStamp
}

答案 3 :(得分:15)

如果您需要经常将字符串解析为日期,则可能需要将该功能移动到扩展名中。我创建了一个sharedCode.swift文件并将我的扩展名放在那里:

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

然后,如果你想将你的字符串转换成NSDate,你可以写一些像:

var myDate = myDateString.toDateTime()

答案 4 :(得分:14)

详细

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

解决方案

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)
    }
}

用法

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)!)")

结果

enter image description here

更多信息

About date format

答案 5 :(得分:9)

适用于Swift 3

{{1}}

答案 6 :(得分:5)

此QA页面上的代码片段是"颠倒" ...

Apple提到的第一件事是你缓存格式化程序......

Link to Apple doco stating exactly how to do this:

  

缓存格式化效率   创建日期格式化程序并不是一个便宜的操作。 ...缓存单个实例......

使用全球......

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

然后只需在任何地方使用该格式化程序......

let s = df.string(from: someDate)

let d = df.date(from: someString)

或者在DateFormatter上使用任何其他许多方便的方法。

就这么简单。

(如果你在String上写了一个扩展名,那么你的代码完全是#34;颠倒了#34; - 你不能使用任何dateFormatter调用!)

请注意,通常你会有一些全局变量..例如" formatForClient" " formatForPubNub" " formatForDisplayOnInvoiceScreen" ..等等。

答案 7 :(得分:4)

Swift支持扩展程序,通过扩展程序,您可以向现有classstructureenumerationprotocol类型添加新功能。

您可以使用init关键字扩展对象,为NSDate对象添加新的extension函数。

extension NSDate
{
    convenience
    init(dateString:String) {
        let dateStringFormatter = NSDateFormatter()
        dateStringFormatter.dateFormat = "yyyyMMdd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "fr_CH_POSIX")
        let d = dateStringFormatter.dateFromString(dateString)!
        self.init(timeInterval:0, sinceDate:d)
    }
} 

现在您可以使用以下命令初始化NSDate对象:

let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")

答案 8 :(得分:4)

自Swift 3以来,许多NS前缀都被删除了。

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)

答案 9 :(得分:4)

斯威夫特3,4:

2次有用的转化:

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

使用方法: 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)

答案 10 :(得分:3)

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

    }
}

注意:如果错误,这将返回原始字符串

答案 11 :(得分:2)

要在Swift中的日期格式中添加String,我就这样做了

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

cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

答案 12 :(得分:2)

这项工作对我来说..

    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!)
    }

答案 13 :(得分:0)

Swift: iOS
if we have string, convert it to NSDate,

var dataString = profileValue["dob"] as String
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"

// convert string into date
let dateValue:NSDate? = dateFormatter.dateFromString(dataString)

if you have and date picker parse date like this

// to avoid any nil value
if let isDate = dateValue {
self.datePicker.date = isDate
}

答案 14 :(得分:0)

以下是一些字符串到日期格式转换选项,可以在迅速的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

答案 15 :(得分:0)

您可以尝试使用此快速代码

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"//same as strDate date formator
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00")//Must used if you get one day less in conversion
    let convertedDateObject = dateFormatter.date(from: strDate)

答案 16 :(得分:0)

SWIFT 5 Xcode 11.0

以所需的“ dateString”和“ dateFormat”传递格式传递(字符串中的日期)。要选择格式,请使用NDateFormatter website

func getDateFrom(dateString: String, dateFormat: String) -> Date? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    dateFormatter.locale = Locale(identifier: "en_US")
    guard let date = dateFormatter.date(from: dateString) else {return nil}
    return date
}

答案 17 :(得分:-3)

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