Convert string to date in Swift
Convert the ISO8601 string to date
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = dateFormatter.date(from:isoDate)!Get the date components for year, month, day and hour from the date
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)Finally create a new
Date
object and strip minutes and secondslet finalDate = calendar.date(from:components)
Consider also the convenience formatter ISO8601DateFormatter
introduced in iOS 10 / macOS 10.12:
let isoDate = "2016-04-14T10:44:00+0000"
let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!
How to convert string to date to string in Swift iOS?
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
How can I convert string date to NSDate?
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 NSDateFormatter and DateFormatter classes of Foundation framework for Objective-C and Swift, respectively.
Swift 3 and later (Swift 4 included)
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
How to convert date string into date in swift 3
Use this string class extension
extension String {
func date(format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone =TimeZone.current
let date = dateFormatter.date(from: self)
return date
}
}
use above function like this
let date = "07/06/2017 11:23 AM".date(format:"MM/dd/yyyy HH:mm a")
swift 3 - can not convert string to date
If your are pretty sure that buffers["pubDate"]!
is equal to "Sun, 02 Apr 2017 19:31:18 GMT" (or any date with the same format), then it should be:
var dateBuffer: Date {
let formatter = DateFormatter()
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
let date = formatter.date(from: buffers["pubDate"]!)
return date!
}
Note that the difference is HH:mm:ss
instead of hh:mm:ss
. For reading the hours as 24-clock convention, you should use HH
.
Also, to be more safe -from any unexpected crash-, I'd suggest to do some optional binding, as follows:
var dateBuffer: Date? {
let formatter = DateFormatter()
let str:String? = "Sun, 02 Apr 2017 19:31:18 GMT"
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
if let pubDate = buffers["pubDate"], let date = formatter.date(from: pubDate) {
return date
}
return nil
}
if let myDate = dateBuffer {
print(myDate)
}
Converting a String to a Date in Swift
The date format needs to be for the string you are trying to convert, not the format you want back
so
formatter.dateFormat = "dd MM YYYY"
should be
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
Related Topics
How to Do Transforms on a Calayer
How to Integrate Nsurlconnection with Uiprogressview
"Could Not Find Any Information for Class Named Viewcontroller"
Should I Git Ignore Xcodeproject/Project.Pbxproj File
Generating an Unsigned IPA iOS Application
Swift - How to Get Last Taken 3 Photos from Photo Library
Behavior Differences Between Performblock: and Performblockandwait:
Error Appstore Connect:Missing Purpose String in Info.Plist File
Uipopovercontroller Dealloc Reached While Popover Is Still Visible
How to Make Both Header and Footer in Collection View with Swift
How to Check If iOS App Is in Background
Left-Align Image and Center Text on Uibutton
How to Add a Uitoolbar Programmatically to an iOS App