How to convert string to date to string in Swift i

2019-01-13 12:25发布

This question already has an answer here:

Am learning swift and am struck in converting the date String to NSDate to string. Am getting the date string in this format "Thu, 22 Oct 2015 07:45:17 +0000". I need to show the date in the MM-dd-yyyy format. I tried the following code but, it returns "null".

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
let dateObj = dateFormatter.dateFromString(dateString!)
print("Dateobj: \(dateObj)")

Can anyone please help where am going wrong? Looking forward the help. Thanks in advance.

4条回答
家丑人穷心不美
2楼-- · 2019-01-13 13:01

See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
查看更多
我只想做你的唯一
3楼-- · 2019-01-13 13:08
//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  
查看更多
ら.Afraid
4楼-- · 2019-01-13 13:14

Swift 3:

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 4 this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
查看更多
趁早两清
5楼-- · 2019-01-13 13:20

First, you need to convert your string to NSDate with its format. Then, you change the dateFormatter to your simple format and convert it back to a String.

SWIFT 3

let dateString = "Thu, 22 Oct 2015 07:45:17 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy hh:mm:ss +zzzz"
dateFormatter.locale = Locale.init(identifier: "en_GB")

let dateObj = dateFormatter.date(from: dateString)

dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: dateObj!))")

The printed result is: Dateobj: 10-22-2015

查看更多
登录 后发表回答