I would like to format a date string into a NSDate object, which doesn't sound like a big thing.
The point is, that the date string contains a dot in the timezone value instead of a plus or something else. A date looks like this:
2017-06-04T16:00:00.000Z
I tried format strings like
yyyy-MM-dd'T'HH:mm:ss.ZZZZ
yyyy-MM-dd'T'HH:mm:ss.ZZZ
yyyy-MM-dd'T'HH:mm:ss.Z
Of course I've also checked it on nsdateformatter.com, which works but in xCode the NSDate is always nil.
The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.
The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC). What Z means in date? zero. What is a timestamp example? TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
Show activity on this post. 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.
Thread SafetyOn iOS 7 and later NSDateFormatter is thread safe. In macOS 10.9 and later NSDateFormatter is thread safe so long as you are using the modern behavior in a 64-bit app.
This work for me
var str = "2017-06-04T16:00:00.000Z"
let formato = DateFormatter()
formato.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
formato.timeZone = NSTimeZone(name: "UTC")! as TimeZone
formato.formatterBehavior = .default
var data = formato.date(from: str)
In Objective-C
NSString *strValue = @"2017-06-04T16:00:00.000Z";
NSString *dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
// Or this if you like get in local time
NSString *dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
NSDateFormatter *dateFmtr = [[NSDateFormatter alloc] init];
[dateFmtr setDateFormat: dateFormat];
// You get a NSDate object
NSDate *dateValue = [dateFmtr dateFromString: strValue];
// Or NSString object
NSString *dateValue = [dateFmtr stringFromDate: dateValue];
Other variants for different strings formats.
// 2018-02-28T16:38:33.6873197-05:00
// If you have this string format you can use
NSString *strDate1 = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ";
For more information with complex formats you can see Patterns Date Format Patterns and the Apple's official documentation Preset Date and Time Styles and Date Formatters
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With