简体   繁体   中英

Getting the time elapsed as UILabel (objective-c)

I want to add a custom UILabel to my cell showing how long ago an item was posted. Any good links out there for a simple how to?

I want to add a label to my cell in storyboard, assign it a tag of say 22 and then programmatically calculate the time since the user posted an item.

EDIT: I don't care about my nil value so I have changed my code to below. Now can someone either point me in the right direction to adding a timestamp or throw me a bone? Much appreciated

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *identifier = @"cell";


UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

// Configure the cell...

PFObject *group = [self.groups objectAtIndex:indexPath.row];

UILabel *nameLabel = (UILabel*) [cell viewWithTag:101];
nameLabel.text = [group objectForKey:@"name"];
UILabel *usernameLabel = (UILabel*) [cell viewWithTag:103];
usernameLabel.text = [group objectForKey:@"creatorName"];


return cell;
}
postedDate = // NSDate object of your postedDate
[postedDate timeIntervalSinceDate:[NSDate date];

This will return seconds between dates, then just use some math to get minutes

NSString *strTime=[aryNewsFeedData valueForKey:@"created"][section];

 int days,hours,minutes;

  NSDateFormatter *formatter    = [[NSDateFormatter alloc] init];
  [formatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS'Z'"];
  NSDate *chatTime   = [formatter dateFromString:strTime];

  NSDate *now =[formatter dateFromString:resultString];

  NSTimeInterval secondsBetween = [now timeIntervalSinceDate:chatTime];

  days            = secondsBetween / (60 * 60 * 24);
  secondsBetween -= days * (60 * 60 * 24);
  hours           = secondsBetween / (60 * 60);
  secondsBetween -= hours * (60 * 60);
  minutes         = secondsBetween / 60;

If you have your posted date as an NSDate , have a look at NSCalendar s -components:fromDate:toDate:options to get the elapsed time. That will give you the individual components (hours, minutes, seconds... whatever you're asking for)

NSDateFormatter *df = [NSDateFormatter new];
    NSString *SomeDate = @"22 04 2015";
    [df setDateFormat:@"dd MM yyyy"];       //Remove the time part
    NSString *TodayString = [df stringFromDate:[NSDate date]];
    NSDate *sdate = [df dateFromString:stringDate];
    NSString *TargetDateString = [df stringFromDate:sdate];
    NSTimeInterval time = [[df dateFromString:TargetDateString] timeIntervalSinceDate:[df dateFromString:TodayString]];
    int days = time / 60 / 60/ 24;
    _lableText.text = [NSString stringWithFormat:@"%d",days];

date-and-time-examples And How to calculate time difference in minutes between two dates in iOS
Go through these links.

This might helps you :)

Check out FormatterKit . I believe that's what you're looking for.

Apart from that, when I did not know about the existence of this library, I made this simple class method that returns a formatted timestamp relative to the current time (works for unix timestamps). Just pass a unix timestamp as a string to it, and it will return a string with the relevant timestamp relative to current time:

+ (NSString*) getTimestampForDate:(NSString*)dateString {

    NSDate* sourceDate = [NSDate dateWithTimeIntervalSince1970:[dateString doubleValue]];

    NSDate* currentDate = [NSDate date];

    NSCalendar* currentCalendar = [NSCalendar currentCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;

    NSDateComponents *differenceComponents = [currentCalendar components:unitFlags fromDate:sourceDate toDate:currentDate options:0];

    NSInteger yearDifference = [differenceComponents year];
    NSInteger monthDifference = [differenceComponents month];
    NSInteger dayDifference = [differenceComponents day];
    NSInteger hourDifference = [differenceComponents hour];
    NSInteger minuteDifference = [differenceComponents minute];

    NSString* timestamp;

    if (yearDifference == 0
        && monthDifference == 0
        && dayDifference == 0
        && hourDifference == 0
        && minuteDifference <= 2) {

        //"Just Now"

        timestamp = @"Just Now";

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference == 0
               && minuteDifference < 60) {

        //"13 minutes ago"

        timestamp = [NSString stringWithFormat:@"%ld minutes ago", (long)minuteDifference];

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference == 1) {

        //"1 hour ago" EXACT

        timestamp = @"1 hour ago";

    } else if (yearDifference == 0
               && monthDifference == 0
               && dayDifference == 0
               && hourDifference < 24) {

        timestamp = [NSString stringWithFormat:@"%ld hours ago", (long)hourDifference];

    } else {

        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

        NSString* strDate, *strDate2 = @"";

        if (yearDifference == 0
            && monthDifference == 0
            && dayDifference == 1) {

            //"Yesterday at 10:23 am", "Yesterday at 5:08 pm"
            [formatter setDateFormat:@"hh:mm a"];
            strDate = [formatter stringFromDate:sourceDate];

            timestamp = [NSString stringWithFormat:@"Yesterday at %@", strDate];

        } else if (yearDifference == 0
                   && monthDifference == 0
                   && dayDifference < 7) {

            //"Tuesday at 7:13 pm"

            [formatter setDateFormat:@"EEEE"];
            strDate = [formatter stringFromDate:sourceDate];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:sourceDate];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];

        } else if (yearDifference == 0) {

            //"July 4 at 7:36 am"

            [formatter setDateFormat:@"MMMM d"];
            strDate = [formatter stringFromDate:sourceDate];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:sourceDate];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];

        } else {

            //"March 24 2010 at 4:50 am"

            [formatter setDateFormat:@"d MMMM yyyy"];
            strDate = [formatter stringFromDate:sourceDate];
            [formatter setDateFormat:@"hh:mm a"];
            strDate2 = [formatter stringFromDate:sourceDate];

            timestamp = [NSString stringWithFormat:@"%@ at %@", strDate, strDate2];
        }

        [formatter release];
    }

    return timestamp;
}

I use this method and give it the NSDate or (NSString of my date) of my item as parameter. (in my case, a message). Just remove the first bit with date formatters if you want to pass an NSDate. (I personally use the two methods separately)

+ (NSString *)dateDiff:(NSString *)origDate{

    NSDateFormatter *df = [[NSDateFormatter alloc] init];   // 
    [df setFormatterBehavior:NSDateFormatterBehavior10_4];  // remove this is you want to pass an NSDate as parameter.
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];          // 
    NSDate *convertedDate = [df dateFromString:origDate];   // 

    NSDate *todayDate = [NSDate date];
    double ti = [convertedDate timeIntervalSinceDate:todayDate];
    ti = ti * -1;

    if(ti < 1) {
        return NSLocalizedString(@"REL_TIME_NOW", nil);
    } else  if (ti < 60) {
        return NSLocalizedString(@"REL_TIME_LESS_THAN_MINUTE", nil);
    } else if (ti < 3600) {
        int diff = round(ti / 60);
        if (diff < 2){
            return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_MINUTE", nil), diff];
        }else{
          return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_MINUTES", nil), diff];
        }
    } else if (ti < 86400) {
        int diff = round(ti / 60 / 60);
        if (diff < 2){
            return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_HOUR", nil), diff];
        }else{
            return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_HOURS", nil), diff];
        }
    } else {
        int diff = round(ti / 60 / 60 / 24);
        if (diff < 2){
            return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_DAY", nil), diff];
        }else{
            return [NSString stringWithFormat:NSLocalizedString(@"REL_TIME_DAYS", nil), diff];
        }
    }
}

Here the localized string :

"REL_TIME_NOW"                  = "Right now!";
"REL_TIME_LESS_THAN_MINUTE"     = "Less than a minute ago";
"REL_TIME_MINUTE"               = "%d minute ago";
"REL_TIME_MINUTES"              = "%d minutes ago";
"REL_TIME_HOUR"                 = "%d hour ago";
"REL_TIME_HOURS"                = "%d hours ago";
"REL_TIME_DAY"                  = "%d day ago";
"REL_TIME_DAYS"                 = "%d days ago";

I just don't have the courage to replace them in the code above. :D

This will return a string that says " 3 minutes ago" for example, and works like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM