Reputation: 1379
I have a string:
NSString* string=@"2014-10-02 18:15:00 +0000";
How can I get date object with this string?
I tried:
NSString* string=@"2014-10-02 18:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *mydate = [dateFormatter dateFromString:string];
NSLog(@"mydate = %@",mydate);
mydate
logs null value. I was expecting to log 2014-10-02 18:15:00 +0000.
All I want is to have date object which can be compared to another date object that displays 2014-10-02 18:15:00 +0000 when logged.
Upvotes: 0
Views: 64
Reputation: 11197
You string is in 24 hour format but 'hh' is for 12 hour format. and 'HH' is for 24 hour format. Thats why it was returning null. Try this:
NSString* string=@"2014-10-02 18:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *mydate = [dateFormatter dateFromString:string];
NSLog(@"mydate = %@",mydate);
Hope this helps.. :)
Upvotes: 2
Reputation: 2380
You must have to use "z" instead "Z" for zone
NSString* string=@"2014-10-02 18:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSDate *mydate = [dateFormatter dateFromString:string];
NSLog(@"mydate = %@",mydate);
Upvotes: 1
Reputation: 5174
because you are using hh
which gives 12hr formate date. but you are getting 24hr formate so you have to use HH
which gives 24hr format. For more Details about date formate check Vanya's answer .Here is very good Explaination about almost all format.(Formatting date and time with iPhone SDK?)
Upvotes: 1