Format date string from .000Z to NSDate
I would like to format a date string into an NSDate object, which doesn't seem like a big thing.
The point is that the date string contains a dot in the timezone value instead of a plus or whatever. The date looks like this:
2017-06-04T16:00:00.000Z
I have 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 also checked it on nsdateformatter.com which works, but in xCode NSDate is always zero.
+3
source to share
3 answers
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 options for different string 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 on complex formats, you can see Templates Date Format Formats and Apple's official documentation Preset Date and Time Styles and Date Formats
+2
source to share
I faced the same problem where I always get nil and as a solution you can exclude the .ZZZZ part from the date string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
let dateString = openningTimeString.components(separatedBy: ".")[0]
let myDate = dateFormatter.date(from: dateString)
-1
source to share