I want to convert "2014-07-15 06:55:14.198000+00:00" this string date to NSDate in Swift.
-
Looks like your string "2014-07-15 06:55:14.198000+00:00" is not reachable if you use NSDateFormatter – Alex Peda Jul 16 '14 at 10:14
-
http://userguide.icu-project.org/formatparse/datetime helped me a lot – Shardul Aug 28 '15 at 06:42
-
As a companion resource to all of the answers below, I would highly recommend checking out http://nsdateformatter.com/ – user3344977 Oct 30 '16 at 21:34
-
The old answers here are really **WRONG**. The Apple doco says crystal clear you need to cache the formatter. https://stackoverflow.com/a/42370648/294884 – Fattie Jul 18 '17 at 00:08
-
If you need any helper with the format, http://nsdateformatter.com – Pedro Luz Dec 16 '17 at 11:29
18 Answers
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
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
Edit:
Alternative date time format reference https://unicode-org.github.io/icu/userguide/format_parse/datetime/

- 6,042
- 1
- 31
- 46
-
11Found the solution just need to set "yyyy-MM-dd hh:mm:ss.SSSSxxx" this date format – Shardul Jul 16 '14 at 10:19
-
1I have a date string like this "2014-07-15 06:55:14-0400" and i tried using `yyyy-MM-dd hh:mm:ssZZZ` . But I'm not able to get the date object out of the string. – iamprem Apr 06 '15 at 20:17
-
2@Prem, if you see the output is `"2014-07-15 10:55:14 +0000"` that will be correct. As from `NSDate` description, output of date would be calculated with difference(here, GMT -4 hours). If you want to get the difference between GMT and UTC, which is `-0400` check this [reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimeZone_Class/) – x4h1d Apr 07 '15 at 11:14
-
@x4h1d, Hey I've got it! I made a mistake in `hh` which should be `HH`. Thanks! – iamprem Apr 07 '15 at 16:59
-
The string I am receiving is `"2000-04-25T00:00:00.000Z"` what should the format be? – lmiguelvargasf Oct 01 '15 at 19:39
-
3@ lmiguelvargasf, I think that would be `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. I assumed `Z` is just a character here. Remember, `Z` has a special meaning too. If you want `Z` to specify as `basic hms` than the format would be `yyyy-MM-dd'T'HH:mm:ss.SSSZ`. – x4h1d Oct 02 '15 at 02:42
-
This QA page is one of those rare cases on SO where, all the answers are **simply wrong**. – Fattie Mar 26 '17 at 13:01
-
I was trying the above date format but it wouldn't work in ***Swift 4.0*** though this did: "yyyy-MM-dd HH:mm:ss ZZZ" I hope it helps someone. – uplearned.com Oct 26 '17 at 12:13
-
dateFormatter.date(from:) returns a "Date?", not an NSDate. This is not the answer. – offthat Dec 30 '17 at 02:20
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)
I can do it with this code.

- 2,011
- 7
- 29
- 40

- 2,157
- 1
- 20
- 15
-
5
-
5using `dd` instead of `DD` should help fix the "always January" issue. – Pascal Belloncle Oct 19 '14 at 07:17
-
1The correct version is, `yyyy-MM-dd`, otherwise, the parsed date is stuck in January - I updated the answer to reflect the change. – Zorayr May 13 '15 at 05:19
-
What if I want to pass the current date as string. Will this work? – Arjun Kalidas Nov 03 '16 at 11:39
-
@Zorayr , Kittisak : I am getting the out put, Optional(2014-07-14 18:30:00 +0000) that means, one day is decremented. How can I fix this ? – Vineesh TP Jul 10 '17 at 16:57
-
@VineeshTP: I have configured the time zone to fix this issue. Please check the below line, dateFormatter.timeZone = TimeZone(identifier: "UTC") – ssowri1 Jul 12 '23 at 04:58
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.
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
}

- 2,097
- 20
- 22
Details
- Swift 4, Xcode 9.2
- Swift 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

- 24,482
- 9
- 132
- 127
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:
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:
var myDate = myDateString.toDateTime()

- 2,912
- 1
- 18
- 5
-
1Thanks. It's also possible, though less useful, to write: var myDate = "04-05-2015".toDateTime() I found this handy when setting up test data. – Stephen Watson Nov 02 '15 at 16:57
-
1
-
This does not give me in the format I specify: var date = NSDate(); let dateFormatter = NSDateFormatter(); dateFormatter.dateFormat = "MMMM d, YYYY"; let myDate = dateFormatter.stringFromDate(date); And on top of this if i use your extension like this -> var myDate2 = myDate.toDateTime(); It's giving me a whole different date and not the current date. – Arjun Kalidas Nov 03 '16 at 11:40
For 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)
}

- 606
- 5
- 16
The code fragments on this QA page are "upside down"...
The first thing Apple mentions is that you cache your formatter...
Link to Apple doco stating exactly how to do this:
Cache Formatters for Efficiency Creating 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.
It is that simple.
(If you write an extension on String, your code is completely "upside down" - you can't use any dateFormatter calls!)
Note that usually you will have a few of those globals .. such as "formatForClient" "formatForPubNub" "formatForDisplayOnInvoiceScreen" .. etc.
-
No need to leave them at global scope. You can extend Formatter just declare your properties static. check this http://stackoverflow.com/a/43658213/2303865 – Leo Dabus May 03 '17 at 02:41
Swift support extensions, with extension you can add a new functionality to an existing class
, structure
, enumeration
, or protocol
type.
You can add a new init
function to NSDate
object by extenging the object using the extension
keyword.
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:
let myDateObject = NSDate(dateString:"2010-12-15 06:00:00")

- 396
- 3
- 10
-
I like the init way. Isn't there another way to create the date without using timeInterval? what if nsdate stops having an initializer with a date parameter? how would you solve it? Personally I prefer an init way but I don't know how to overcome this problem – Mijail Feb 09 '16 at 10:31
-
I have an issue: my date as string is like this: "2017-03-10 22:16:00 +0000" and I used this format: "yyyy-MM-dd hh:mm:ss Z" and this one: "yyyy-MM-dd'T'HH:mm:ss". But for both, when I do this: let beginDate = `df.date(from: beginDateString)`, I get a nil! why? (`df = DateFormatter()`) – Paul Bénéteau Mar 06 '17 at 21:50
Since Swift 3, many of the NS prefixes have been dropped.
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)

- 2,863
- 2
- 18
- 33
-
I have an issue: my date as string is like this: "2017-03-10 22:16:00 +0000" and I used this format: "yyyy-MM-dd hh:mm:ss Z" and this one: "yyyy-MM-dd'T'HH:mm:ss". But for both, when I do this: let beginDate = `df.date(from: beginDateString)`, I get a nil! why? (`df = DateFormatter()`) – Paul Bénéteau Mar 06 '17 at 21:50
Swift 3,4:
2 useful conversions:
string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date
Usage: 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)

- 11,885
- 4
- 72
- 54
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
}
}
NOTE: THIS WILL RETURN THE ORIGINAL STRING IF ERROR

- 1,176
- 18
- 21
To add String within Date Format in Swift, I did this
var dataFormatter:NSDateFormatter = NSDateFormatter()
dataFormatter.dateFormat = "dd-MMMM 'at' HH:mm a"
cell.timeStamplbl.text = dataFormatter.stringFromDate(object.createdAt)

- 1,735
- 19
- 19
This work for me..
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!)
}

- 624
- 7
- 21
You can try this swift code
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)

- 1,302
- 15
- 12
Below are some string to date format converting options can be usedin swift 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

- 893
- 9
- 10
SWIFT 5, Xcode 11.0
Pass your (date in string) in "dateString" and in "dateFormat" pass format you want. To choose format, use 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
}

- 4,256
- 1
- 26
- 30
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
}

- 7,696
- 1
- 50
- 51
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

- 19
- 3
-
2How is this supposed to work? The date formatter is not initialized and there's also no reason to split the declaration and initialization of date. – User Jul 22 '15 at 17:52