Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format date string with .000Z into NSDate

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.

like image 861
user3191334 Avatar asked May 26 '17 17:05

user3191334


People also ask

How do I format a date string?

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.

What is 000z in timestamp?

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.

How do you string convert in to date in Swift?

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.

Is NSDateFormatter thread safe?

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.


2 Answers

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)
like image 106
Claudio Castro Avatar answered Oct 10 '22 13:10

Claudio Castro


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

like image 25
Ladd.c Avatar answered Oct 10 '22 14:10

Ladd.c