iOS-дружественный формат NSDate

Мне нужно отобразить дату сообщений в моем приложении для пользователя, прямо сейчас я делаю это в следующем формате:"Пт, 25 мая". Как бы я отформатировал NSDate, чтобы прочитать что-то вроде "2 часа назад"? Чтобы сделать его более удобным.

9 ответов


NSDateFormatter Не могу делать такие вещи; вам нужно будет установить свои собственные правила. Я думаю, что-то вроде:

- (NSString *)formattedDate:(NSDate *)date
{
     NSTimeInterval timeSinceDate = [[NSDate date] timeIntervalSinceDate:date];

     // print up to 24 hours as a relative offset
     if(timeSinceDate < 24.0 * 60.0 * 60.0)
     {
         NSUInteger hoursSinceDate = (NSUInteger)(timeSinceDate / (60.0 * 60.0));

         switch(hoursSinceDate)
         {
              default: return [NSString stringWithFormat:@"%d hours ago", hoursSinceDate];
              case 1: return @"1 hour ago";
              case 0:
                  NSUInteger minutesSinceDate = (NSUInteger)(timeSinceDate / 60.0);
                  /* etc, etc */
              break;
         }
     }
     else
     {
          /* normal NSDateFormatter stuff here */
     }
}

Так что это для печати "x минут назад" или "x часов назад" до 24 часов с даты, которая обычно будет один день.


взгляните на FormaterKit https://github.com/mattt/FormatterKit

создано mattt, который также создал AFNetworking.


Я хотел формат даты, как Facebook делает для своих мобильных приложений, поэтому я взбил эту категорию NSDate-надеюсь, это полезно для кого-то (такие вещи действительно должны быть в стандартной библиотеке!):)

https://github.com/nikilster/NSDate-Time-Ago


есть также SEHumanizedTimeDiff, который / собирается поддерживать несколько языков, если это проблема для вас:

https://github.com/sarperdag/SEHumanizedTimeDiff


есть около миллиона способов сделать это, но вот быстрый:

NSString* hoursAgo = [NSString stringWithFormat:@"%.0lf hours ago", fabs([date timeIntervalSinceNow] / 3600.0)]

конечно, это не проверяет, что date на самом деле из прошлого, ничего не делает, кроме часов и т. д. Но ты, наверное, понимаешь.

timeIntervalSinceNow возвращает, сколько секунд прошло с заданной даты, причем положительные числа являются датой в будущем, а отрицательные-датой в прошлом. Итак, мы получаем, сколько секунд прошло, делим его на 3600 секунд в час, чтобы вычислить часы, которые прошли, а затем поместить его абсолютное значение в строку "n часов назад".


вот довольно хороший ответ, который займет несколько секунд с момента эпохи (1 января 1970 года) и вернет вам хорошую форматированную строку, такую как "3 минуты назад". Просто вызовите его с помощью объекта date следующим образом:

[timeAgoFromUnixTime:[myDateObject timeIntervalSince1970]];

+ (NSString *)timeAgoFromUnixTime:(double)seconds
{
    double difference = [[NSDate date] timeIntervalSince1970] - seconds;
    NSMutableArray *periods = [NSMutableArray arrayWithObjects:@"second", @"minute", @"hour", @"day", @"week", @"month", @"year", @"decade", nil];
    NSArray *lengths = [NSArray arrayWithObjects:@60, @60, @24, @7, @4.35, @12, @10, nil];
    int j = 0;
    for(j=0; difference >= [[lengths objectAtIndex:j] doubleValue]; j++)
    {
        difference /= [[lengths objectAtIndex:j] doubleValue];
    }
    difference = roundl(difference);
    if(difference != 1)
    {
        [periods insertObject:[[periods objectAtIndex:j] stringByAppendingString:@"s"] atIndex:j];
    }
    return [NSString stringWithFormat:@"%li %@%@", (long)difference, [periods objectAtIndex:j], @" ago"];
}

в более новых версиях iOS, так как этот вопрос был задан, NSDateFormatter была добавлена эта способность. Теперь он может сделать это с помощью doesRelativeDateFormatting собственность.


+(NSString*)HourCalculation:(NSString*)PostDate

{
    NSLog(@"postdate=%@",PostDate);
    // PostDate=@"2014-04-02 01:31:04";
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormat setTimeZone:gmt];
    NSDate *ExpDate = [dateFormat dateFromString:PostDate];
    NSLog(@"expdate=%@",ExpDate);
    NSLog(@"expdate=%@",[NSDate date ]);
    NSCalendar *calendar = [NSCalendar currentCalendar];

    NSDateComponents *components = [calendar components:(NSDayCalendarUnit|NSWeekCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:ExpDate toDate:[NSDate date] options:0];

//    NSLog(@"year=%d",components.year);
//    
//    NSLog(@"month=%d",components.month);
//    
//    NSLog(@"week=%d",components.week);
//    
//    NSLog(@"day=%d",components.day);
//    
//    NSLog(@"hour=%d",components.hour);
//    
//    NSLog(@"min=%d",components.minute);
//    
//    NSLog(@"sce=%d",components.second);
//    

    NSString *time;

    if(components.year!=0)   
    {
        if(components.year==1) 
        {
            time=[NSString stringWithFormat:@"%ld year",(long)components.year];  
        }
        else{
            time=[NSString stringWithFormat:@"%ld years",(long)components.year]; 
        }    
    }
    else if(components.month!=0) 
    {
        if(components.month==1)   
        {
            time=[NSString stringWithFormat:@"%ld month",(long)components.month]; 
        }
        else{
            time=[NSString stringWithFormat:@"%ld months",(long)components.month]; 
        }
      //  NSLog(@"%@",time);
    }
    else if(components.week!=0)
    {
        if(components.week==1)
        {
            time=[NSString stringWithFormat:@"%ld week",(long)components.week];
        }
        else{
            time=[NSString stringWithFormat:@"%ld weeks",(long)components.week];
        }
       // NSLog(@"%@",time);
    }
    else if(components.day!=0)
    {
        if(components.day==1)   
        {
            time=[NSString stringWithFormat:@"%ld day",(long)components.day];
        }
        else{
            time=[NSString stringWithFormat:@"%ld days",(long)components.day]; 
        } 
    }
    else if(components.hour!=0) 
    {
        if(components.hour==1)  
        {
            time=[NSString stringWithFormat:@"%ld hour",(long)components.hour];  
        }
        else{
            time=[NSString stringWithFormat:@"%ld hours",(long)components.hour];
        }
    }
    else if(components.minute!=0)  
    {
        if(components.minute==1)  
        {
            time=[NSString stringWithFormat:@"%ld min",(long)components.minute];
        }

        else{
            time=[NSString stringWithFormat:@"%ld mins",(long)components.minute]; 
        }
      //  NSLog(@"time=%@",time);
    }
    else if(components.second>=0){

       // NSLog(@"postdate=%@",PostDate);

       // NSLog(@"expdate=%@",[NSDate date ]);

        if(components.second==0)   
        {
            time=[NSString stringWithFormat:@"1 sec"];
        }
        else{
            time=[NSString stringWithFormat:@"%ld secs",(long)components.second];
        }
    }
    return [NSString stringWithFormat:@"%@ ago",time];

}

этот код покажет вам время в ------------ сек, как 2 сек назад ------------ мин, как 2 мин назад ------------часа как 2 часа назад ------------ дней, как 2 дня назад -----------недели как 2 недели назад ------------месяц, как 2 месяца назад Наконец.... лет как 2 года назад. :) попробуйте это


добавление в решение попробуйте этот более упрощенный метод

    NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:passed toDate:[NSDate date] options:0];
    NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];

    if (interval < 60) timestampString = [NSString stringWithFormat:@"%d seconds ago" ,today.second];
    else if (interval < 60 * 60) timestampString = [NSString stringWithFormat:@"%d minutes ago" ,today.minute];
    else if (interval < 60 * 60 * 24) timestampString = [NSString stringWithFormat:@"%d hours ago" ,today.hour];
    else timestampString = [NSString stringWithFormat:@"%d days ago" ,today.day];