如何将stringdate转换为NSDate?
我想在Swift中把“2014-07-15 06:55:14.198000 + 00:00”这个string的date转换成NSDate。
尝试这个:
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 */)
进一步的查询请参阅文档 。
Swift 3和更高版本
let dateFormatter = DateFormatter() dateFormatter.dateFormat = /* date_format_you_want_in_string from * http://userguide.icu-project.org/formatparse/datetime */ let date = dateFormatter.date(from: /* your_date_string */)
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)
我可以用这个代码来做。
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 }
如果您需要经常将stringparsing为date,则可能需要将该function移到扩展中。 我创build了一个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 } }
那么如果你想把你的string转换成一个NSDate,你可以只写如下的东西:
var myDate = myDateString.toDateTime()
细节
Swift 3,xCode 8.2.1
date格式的扩展
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) } }
用法
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")!)")
结果
更多信息
关于date格式
对于Swift 3
func stringToDate(_ str: String)->Date{ let formatter = DateFormatter() formatter.dateFormat="yyyy-MM-dd hh:mm:ss Z" return formatter.date(from: str)! } func dateToString(_ str: Date)->String{ var dateFormatter = DateFormatter() dateFormatter.timeStyle=DateFormatter.Style.short return dateFormatter.string(from: str) }
Swift支持扩展,通过扩展可以为现有的class
, structure
, enumeration
或protocol
types添加新的function。
您可以通过使用extension
关键字extension
对象来将新的init
函数添加到NSDate
对象。
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")
自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)
这个QA页面上的代码片段是“颠倒的”…
苹果提到的第一件事是你caching你的格式化程序…
链接到苹果doco,说明如何做到这一点:
高速caching格式化程序创builddate格式化程序不是一个便宜的操作。 caching单个实例…
使用全球…
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上编写扩展,你的代码是完全颠倒的 – 你不能使用任何的dateFormatter调用!)
请注意,通常你会有一些全局的..如“formatForClient”“formatForPubNub”“formatForDisplayOnInvoiceScreen”..等
要在Swift中的date格式中添加string,我做了这个
var dataFormatter:NSDateFormatter = NSDateFormatter() dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a" cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)
对于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 } }
注意:这将返回原来的string,如果错误
Swift 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)
这个工作对我来说..
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!) }
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 }
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