I want to convert nsdate in to relative format like "Today","Yesterday","a week ago","a month ago","a year ago","date as it is"
.
I have written following method for it.. but some how its just printing as it is date.. can you please tell me what should be the problem?
//Following is my function which converts the date into relative string
+(NSString *)getDateDiffrence:(NSDate *)strDate{
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.timeStyle = NSDateFormatterMediumStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.doesRelativeDateFormatting = YES;
NSLog(@"STRING DATEEE : %@ REAL DATE TODAY %@",[df stringFromDate:strDate],[NSDate date]);
return [df stringFromDate:strDate];
}
I have date string with the following format "2013-10-29T09:38:00"
When I tried to give the NSDate object then its always return me null date.
so I tried to convert that date in to yyyy-MM-dd HH:mm:ssZZZZ
then I pass this date to function then it's just printing whole date..
How to solve this problem?
//Following is the code I call the above function
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [formatter dateFromString:[threadDict objectForKey:@"lastMessageDate"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZZ"];
NSString *date1 = [formatter stringFromDate:date];
NSDate *date_d = [formatter dateFromString:date1];
NSString *resultstr=[UserManager getDateDiffrence:date];
self.dateLabel.text=resultstr;
check NSDate-TimeAgo, it also supports multiple languages.
To format the given "sourceDate" as "5:56 pm" for today, "yesterday" for any time yesterday, "January 16" for any day in the same year and "January 16, 2014". I am posting my own method.
Here is code I created for my use:
Here's my answer (in Swift 3!) and why it's better.
Answer:
Remember to reuse your formatters to avoid any performance hit! Hint: extensions on DateFormatter and DateComponentsFormatter are good ideas.
Why it's better:
I have attached demo here please find on this link. TimestampAgo-Demo
Thanks to n00bprogrammer
Edit :- I made changes in Sourcetimezone with [NSTimeZone systemTimeZone] because due to static time zone , issue occure in GMT or UTC format. (second goes in minus) and change deprecated Methods.
Here is my solution in Swift 2 that avoid 24-hour problem by comparing two dates with a zero time.