Objective C - Date formate (hours ago, min ago)

Posted on   24-01-2012 12:23 by admin

iPhone: Convert date string to a relative time stamp

Given date should be converted to years, months, hours, min ago type

@interface NSDate (NSDate_Relativity)

-(NSString *)distanceOfTimeInWordsSinceDate:(NSDate *)aDate;
-(NSString *)distanceOfTimeInWordsToNow;

@end



@implementation NSDate (NSDate_Relativity)


-(NSString *)distanceOfTimeInWordsToNow {
return [self distanceOfTimeInWordsSinceDate:[NSDate date]];

}

-(NSString *)distanceOfTimeInWordsSinceDate:(NSDate *)aDate {
double interval = [self timeIntervalSinceDate:aDate];

NSString *timeUnit;
int timeValue;

if (interval < 0) {
interval = interval * -1;
}

if (interval< 60) {
return @"seconds";

} else if (interval< 3600) { // minutes

timeValue = round(interval / 60);

if (timeValue == 1) {
timeUnit = @"minute";

} else {
timeUnit = @"minutes";

}


} else if (interval< 86400) {
timeValue = round(interval / 60 / 60);

if (timeValue == 1) {
timeUnit = @"hour";

} else {
timeUnit = @"hours";
}


} else if (interval< 2629743) {
int days = round(interval / 60 / 60 / 24);

if (days < 7) {

timeValue = days;

if (timeValue == 1) {
timeUnit = @"day";
} else {
timeUnit = @"days";
}

} else if (days < 30) {
int weeks = days / 7;

timeValue = weeks;

if (timeValue == 1) {
timeUnit = @"week";
} else {
timeUnit = @"weeks";
}


} else if (days < 365) {

int months = days / 30;
timeValue = months;

if (timeValue == 1) {
timeUnit = @"month";
} else {
timeUnit = @"months";
}

} else if (days < 30000) { // this is roughly 82 years. After that, we'll say 'forever'
int years = days / 365;
timeValue = years;

if (timeValue == 1) {
timeUnit = @"year";
} else {
timeUnit = @"years";
}

} else {
return @"forever ago";
}
}

return [NSString stringWithFormat:@"%d %@", timeValue, timeUnit];

}

@end

    Source: http://stackoverflow.com/questions/902950/iphone-convert-date-string-to-a-relative-time-stamp
    Link: http://stackoverflow.com/questions/902950/iphone-convert-date-string-to-a-relative-time-stamp
Comments:
    Tommy on   28-06-2012 22:53
    I think, and this is just an observation, that if you exsreice in the morning, that's great because it gets the blood flowing and gives you a lot of energy to start off your day, During the day, if you're a busy person, wouldn't you also get more ex
    John on   04-01-2016 20:06
    That's right, doing exercise in the morning is far better. That gives more energy to start the day
    my blog on   12-07-2017 05:02
    I am regular visitor, how are you everybody? This article posted at this website is really good. my blog http://www.chelseachris.com/UserProfile/tabid/57/userId/406795/Default.aspx
 

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.