ios 如何将字符串日期转换为 NSDate?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24777496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert string date to NSDate?
提问by Shardul
I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift.
我想在 Swift 中将“2014-07-15 06:55:14.198000+00:00”这个字符串日期转换为 NSDate。
回答by x4h1d
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 NSDateFormatterand DateFormatterclasses of Foundationframework for Objective-C and Swift, respectively.
如需进一步查询,请分别检查Objective-C 和 Swift的Foundation框架的NSDateFormatter和DateFormatter类。
Swift 3 and later (Swift 4 included)
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
回答by Kiattisak Anoochitarom
Swift 4
斯威夫特 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
斯威夫特 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)
I can do it with this code.
我可以用这段代码做到这一点。
回答by idris y?ld?z
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
}
Updated for Swift 3.
为 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
}
回答by Vasily Bodnarchuk
Details
细节
- Swift 4, Xcode 9.2
- Swift 5, Xcode 10.2 (10E125)
- 斯威夫特 4,Xcode 9.2
- 斯威夫特 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
更多信息
回答by user2266987
If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:
如果您需要经常将字符串解析为日期,您可能希望将该功能移至扩展中。我创建了一个 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
}
}
Then if you want to convert your string into a NSDate you can just write something like:
然后,如果您想将字符串转换为 NSDate,您可以编写如下内容:
var myDate = myDateString.toDateTime()
回答by Rishabh Dugar
For Swift 3
对于 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)
}
回答by Fattie
The code fragments on this QA page are "upside down"...
这个 QA 页面上的代码片段是“颠倒的”......
The first thing Apple mentions is that you cache your formatter...
苹果提到的第一件事是你缓存你的格式化程序......
Link to Apple doco stating exactly how to do this:
指向 Apple doco 的链接,具体说明如何执行此操作:
Cache Formatters for EfficiencyCreating 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.
或者使用 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!)
(如果你在 String 上写一个扩展,你的代码是完全“颠倒的”——你不能使用任何 dateFormatter 调用!)
Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.
请注意,通常您会有一些全局变量 .. 例如 "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. 等。
回答by Naishta
Swift 3,4:
斯威夫特 3,4:
2 useful conversions:
2个有用的转换:
string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date
Usage: 1.
用法:1。
let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)
2.
2.
let someDateInString = "23.06.2017"
var getDateFromString = dateFormatter.date(from: someDateInString)
回答by Hugo Pereira
Swift support extensions, with extension you can add a new functionality to an existing class
, structure
, enumeration
, or protocol
type.
斯威夫特支持扩展,扩展名为您可以到现有的添加新的功能class
,structure
,enumeration
,或protocol
类型。
You can add a new init
function to NSDate
object by extenging the object using the extension
keyword.
您可以通过使用关键字扩展对象来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)
}
}
Now you can init a NSDate object using:
现在您可以使用以下命令初始化一个 NSDate 对象:
let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")
回答by toddg
Since Swift 3, many of the NS prefixes have been dropped.
自 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)