我想将“2014-07-15 06:55:14.198000 + 00:00”这个字符串日期转换为Swift中的NSDate。
答案 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 框架的NSDateFormatter和DateFormatter类。
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)
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)!)")
答案 5 :(得分:9)
适用于Swift 3
{{1}}
答案 6 :(得分:5)
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支持扩展程序,通过扩展程序,您可以向现有class
,structure
,enumeration
或protocol
类型添加新功能。
您可以使用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中使用。
Thursday, Dec 27, 2018
format = EEEE, MMM d, yyyy
12/27/2018
format = MM/dd/yyyy
12-27-2018 09:59
format = MM-dd-yyyy HH:mm
Dec 27, 9:59 AM
format = MMM d, h:mm a
December 2018
format = MMMM yyyy
Dec 27, 2018
format = MMM d, yyyy
Thu, 27 Dec 2018 09:59:19 +0000
format = E, d MMM yyyy HH:mm:ss Z
2018-12-27T09:59:19+0000
format = yyyy-MM-dd'T'HH:mm:ssZ
27.12.18
format = dd.MM.yy
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