The time difference between objective-C calculation and the present

Source: Internet
Author: User

Recently, a small application was developed to read Sina Weibo. The newly published Weibo posts on Weibo do not tell you when to release it, but tell you the time relative to the current time a few seconds ago, a few minutes ago, or a few hours ago. You can use the following code to calculate the time difference.

- (NSString*)timestamp
{
// Calculate distance time string
//
time_t now;
time(&now);

int distance = (int)difftime(now, createdAt);
if (distance < 0) distance = 0;

if (distance < 60) {
self.timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance == 1) ? "second ago" : "seconds ago"];
}
else if (distance < 60 * 60) {
distance = distance / 60;
self.timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance == 1) ? "minute ago" : "minutes ago"];
}
else if (distance < 60 * 60 * 24) {
distance = distance / 60 / 60;
self.timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance == 1) ? "hour ago" : "hours ago"];
}
else if (distance < 60 * 60 * 24 * 7) {
distance = distance / 60 / 60 / 24;
self.timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance == 1) ? "day ago" : "days ago"];
}
else if (distance < 60 * 60 * 24 * 7 * 4) {
distance = distance / 60 / 60 / 24 / 7;
self.timestamp = [NSString stringWithFormat:@"%d %s", distance, (distance == 1) ? "week ago" : "weeks ago"];
}
else {
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
}

NSDate *date = [NSDate dateWithTimeIntervalSince1970:createdAt];
self.timestamp = [dateFormatter stringFromDate:date];
}
return timestamp;
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.