TKutal TKutal - 5 months ago 27
Objective-C Question

Convert NSString to NSDate without changing format

I know this has been asked a lot of time but all the solutions I tried changed the format to the NSDate which is not what I want. So I have a

which I need to convert into NSDate AS IT IS. I tried the following code:

NSString *newDate = @"2016-08-15T00:00:01.000Z"

NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateStyle:kCFDateFormatterNoStyle];
[dateFormater setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormater dateFromString:newDate];

But it changed the format to
2016-08-18 18:30:00 +0000
which is not what I want. Can someone help me, thanks in advance.


But it changed the format to 2016-08-18 18:30:00 +0000

An NSDate does not have a format, in the same way an int or a double do not have a format. Internally an NSDate is represented as the number of seconds since the reference date.

When you talk about "format" you are talking about a textual representation, and the same value can have different textual representations. For example "three", "3", and "III" are all textual representations of the number 3 - the number itself has no format but can be represented (formatted) in different ways.

Try adding these three lines to your code:

NSString *stringFromDate1 = [dateFormater stringFromDate:dateFromString];
NSString *stringFromDate2 = [dateFromString description];
NSLog(@"%@ | %@ | %@", dateFromString, stringFromDate1, stringFromDate2);

What is the output? stringFromDate1 is the date value represented in your original format, while stringFromDate2 is the format produced by the description method - they are the same date, just formatted differently. And as running the above code will show you, if NSLog is passed a non-string object it calls its description method to obtain a textual representation of it which it can then output.

Hopefully that all makes sense!

TL;DR: non-string data types don't have formats, they can be converted to and from textual representations.