Reputation: 270
I need to convert String as a date and then preset it in a UILabel. When I do this like below, I get null string and the UILabel is also null. What is wrong in this code?
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd, YYYY HH:mm:ss"];
NSDate *dateFromString;
dateFromString = [dateFormat dateFromString:[tmpDevice valueForKey:@"date"]]; //This string is from array of object and is not null
NSString *stringFromDate = [dateFormat stringFromDate:dateFromString];
NSLog(@"%@", stringFromDate); // here is null
[cell.dateOfAddedCell setText: stringFromDate]; // and here also is null
Upvotes: 0
Views: 143
Reputation: 4277
Try to replace this line:
dateFromString = [dateFormat dateFromString:[tmpDevice valueForKey:@"date"]];
with something like:
dateFromString = [NSDate dateWithTimeIntervalSince1970:[(NSNumber *) [tmpDevice valueForKey:@"date"] intValue]];
Your code is not working because [tmpDevice valueForKey:@"date"] should return something like:
@"May 25, 20145 19:30:00"
but not:
1406141698811
in case you wish to use the method:
dateFromString
Hope it makes sense
Upvotes: 1
Reputation: 318944
Based on your comments, you have a string representing the milliseconds. You first need to convert that string to an NSDate
. Then you can format the NSDate
into the desired string.
You neglect to mention the epoch for your value but it appears to be based on the standard January 1, 1970 epoch.
NSString *millisString = tmpDevice[@"data"];
NSTimeInterval seconds = [miliisString doubleValue] / 1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd, yyyy HH:mm:ss"]; // notice is yyyy, not YYYY
NSString *stringFromDate = [dateFormat stringFromDate:date];
NSLog(@"%@", stringFromDate);
cell.dateOfAddedCell.text = stringFromDate;
Upvotes: 1