Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to date with NSDateFormatter

Im trying to convert this string '2015-05-08T09:44:25.343' format to date 'dd/MM/YYYY' format

What I`m doing wrong? my date comes Nil.

// convert 2015-05-08T09:44:25.343 to dd/MM/yyyy

NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"dd/MM/yyyy"];
NSDate *date = [dateFormat dateFromString:str];

NSLog(@"%@",date);        
NSString *convertedString = [dateFormat stringFromDate:date]; 
NSLog(@"%@", convertedString);
like image 909
ErasmoOliveira Avatar asked Apr 15 '26 22:04

ErasmoOliveira


1 Answers

NSString *str = @"2015-05-08T09:44:25.343";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"];// this string must match given string @"2015-05-08T09:44:25.343"

NSDate *date = [dateFormat dateFromString:str];

NSLog(@"%@",date);
[dateFormat setDateFormat:@"MM/dd/yyyy"];// this match the one you want to be        
NSString *convertedString = [dateFormat stringFromDate:date]; 
NSLog(@"%@", convertedString);
like image 63
Zy Zhao Avatar answered Apr 18 '26 12:04

Zy Zhao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!