Reputation: 1805
I have come across a lot of links on stackoverflow and tried to implement code to convert timestamp in this format 2013-07-20T12:23:54.411+05:30 to NSDate of this format
July 20, 2013 (Tuesday) 12:23:54 Or 1 minute ago, 2 days ago format.
I have implemented the following code. The toDate is nil i.e date1 is giving nil value. Seems like Xcode is being sarcastic for this issue
I mean really, what do you think that operation is supposed to mean with a nil toDate? An exception has been avoided for now. A few of these errors are going to be reported with this complaint, then further violations will simply silently do whatever random thing results from the nil.
Could anyone tell me where i have gone wrong?
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:@"yyyy-mm-ddTHH:mm:ssssZ"];
[dateForm setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[dateForm setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = [dateForm dateFromString:string];
NSDate *date2 = [NSDate date];
unsigned int unitFlags = NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
// gets the difference between the current date and also the date and time in the timestamp of the data
NSDateComponents *diffComps = [cal components:unitFlags fromDate:date2 toDate:date1 options:0];
int year = ABS([diffComps year]);
int month = ABS([diffComps month]);
int day = ABS([diffComps day]);
int hour = ABS([diffComps hour]);
int minute = ABS([diffComps minute]);
int seconds = ABS([diffComps second]);
NSString *displayTime;
if (year == 0) {
if (month == 0) {
if (day == 0) {
if (hour == 0){
if (minute == 0) {
displayTime = [NSString stringWithFormat:@"about %d secs ago",seconds];
}
else {
displayTime = [NSString stringWithFormat:@"about %d mins ago",minute];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d hours ago",hour];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d days ago",day];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d months ago",month];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d years ago",year];
}
EDIT: This works fine with a string that i have created in the appdelegate. But not the string I have created in a singleton class.
Upvotes: 1
Views: 223
Reputation: 122401
You are not using the correct time format; I would suggest this:
yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ
Upvotes: 2