Smart Formatting of time span

前端 未结 3 2021
抹茶落季
抹茶落季 2021-02-04 16:40

I need a method to format a NSTimeInterval (time span in seconds) into a string to produce something like \"about 10 minutes ago\", \"1h, 20min\",

3条回答
  •  盖世英雄少女心
    2021-02-04 17:09

    This is a category for NSDate. It's not exactly using an NSTimeInterval, well internally :) I assume you are working with timestamps.

    Header file NSDate+PrettyDate.h

    @interface NSDate (PrettyDate)
    
    - (NSString *)prettyDate;
    
    @end
    

    Implementation NSDate+PrettyDate.m

    @implementation NSDate (PrettyDate)
    
    - (NSString *)prettyDate
    {
        NSString * prettyTimestamp;
    
        float delta = [self timeIntervalSinceNow] * -1;
    
        if (delta < 60) {
            prettyTimestamp = @"just now";
        } else if (delta < 120) {
            prettyTimestamp = @"one minute ago";
        } else if (delta < 3600) {
            prettyTimestamp = [NSString stringWithFormat:@"%d minutes ago", (int) floor(delta/60.0) ];
        } else if (delta < 7200) {
            prettyTimestamp = @"one hour ago";      
        } else if (delta < 86400) {
            prettyTimestamp = [NSString stringWithFormat:@"%d hours ago", (int) floor(delta/3600.0) ];
        } else if (delta < ( 86400 * 2 ) ) {
            prettyTimestamp = @"one day ago";       
        } else if (delta < ( 86400 * 7 ) ) {
            prettyTimestamp = [NSString stringWithFormat:@"%d days ago", (int) floor(delta/86400.0) ];
        } else {
            NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
            [formatter setDateStyle:NSDateFormatterMediumStyle];
    
            prettyTimestamp = [NSString stringWithFormat:@"on %@", [formatter stringFromDate:self]];
            [formatter release];
        }
    
        return prettyTimestamp;
    }
    

提交回复
热议问题