Reputation: 5107
In my app I have a string 'date'="2015-03-16".
I need to show it in a label as Lunes 16 de marzo 2015 (Monday 16 March 2015). I am using the following code to do it:
NSString *dateStr = date;
// Convertimos el string date a objeto de fecha
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-d"];
NSDate *fecha = [dateFormat dateFromString:dateStr];
NSLog(@"DATE CONVERTIDO A FECHA =%@", fecha);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEEE, dd MMM yyyy"];
fecha = [df dateFromString: date];
NSLog(@"date: %@", fecha);
But at the end I get (null) for the variable 'fecha'
Log --> date: (null)
What am I doing wrong?
Upvotes: 0
Views: 63
Reputation: 6342
You were using format @"yyyy-MM-d"
, Use @"yyyy-MM-dd"
NSString *dateStr = date;
// Convertimos el string date a objeto de fecha
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];//You were using only d
dateFormat.dateStyle = NSDateFormatterFullStyle
NSDate *fecha = [dateFormat dateFromString:dateStr];
NSLog(@"DATE CONVERTIDO A FECHA =%@", fecha);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEEE, dd MMM yyyy"];
NSString *newDatestr = [df stringFromDate:fecha];
NSLog(@"date: %@", newDatestr);
Upvotes: 1
Reputation: 1521
You are going in opposite direction after your df
formatter replace your code with this:
NSString *dateStr=@"2015-03-16";
// Convertimos el string date a objeto de fecha
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *fecha = [dateFormat dateFromString:dateStr];
NSLog(@"DATE CONVERTIDO A FECHA =%@", fecha);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEEE, dd MMM yyyy"];
NSString *newDatestr = [df stringFromDate:fecha];
NSLog(@"date: %@", newDatestr);
Hope it helps...........:)
Upvotes: 1
Reputation: 437442
Your df
formatter code is doing another dateFromString
And I think you intended to go the other direction for this second formatter (e.g. stringFromDate
of the fecha
previously determined).
Upvotes: 1