Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
iOS友好的NSDate格式_Ios_Date_Nsdate_Nsdateformatter_Date Format - Fatal编程技术网

iOS友好的NSDate格式

iOS友好的NSDate格式,ios,date,nsdate,nsdateformatter,date-format,Ios,Date,Nsdate,Nsdateformatter,Date Format,我需要在我的应用程序中向用户显示帖子的日期,现在我使用这种格式:“5月25日星期五”。如何将NSDate格式化为“2小时前”之类的格式?使其更加用户友好。请查看FormatterKit 由mattt创建,他还创建了AFNetworking 有大约一百万种方法可以做到这一点,但这里有一个简单的方法: NSString* hoursAgo = [NSString stringWithFormat:@"%.0lf hours ago", fabs([date timeIntervalSinceNow]

我需要在我的应用程序中向用户显示帖子的日期,现在我使用这种格式:“5月25日星期五”。如何将NSDate格式化为“2小时前”之类的格式?使其更加用户友好。

请查看FormatterKit


由mattt创建,他还创建了AFNetworking

有大约一百万种方法可以做到这一点,但这里有一个简单的方法:

NSString* hoursAgo = [NSString stringWithFormat:@"%.0lf hours ago", fabs([date timeIntervalSinceNow] / 3600.0)]
当然,这并没有检查日期是否确实是过去的,除了小时之外什么都不做,等等。但是,你可能知道了


timeIntervalSinceNow
返回给定日期后经过的秒数,正数表示将来的日期,负数表示过去的日期。因此,我们得到已经过去的秒数,除以一小时内3600秒来计算已经过去的小时数,然后将其绝对值放入字符串“n小时前”。

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 */
     }
}
-(NSString*)格式化日期:(NSDate*)日期
{
NSTimeInterval timeSinceDate=[[NSDate date]timeIntervalSinceDate:date];
//以相对偏移量打印最多24小时
如果(时间间隔<24.0*60.0*60.0)
{
NSUInteger hoursSinceDate=(NSUInteger)(timeSinceDate/(60.0*60.0));
开关(小时/秒/秒)
{
默认值:返回[NSString stringWithFormat:@“%d小时前”,hoursSinceDate];
案例1:返回@“1小时前”;
案例0:
NSUInteger minutesincedate=(NSUInteger)(timeSinceDate/60.0);
/*等等等等*/
打破
}
}
其他的
{
/*这里是正常的NSDateFormatter内容*/
}
}

因此,这意味着打印“x分钟前”或“x小时前”,打印时间最长为24小时,通常为一天。

还有SEHumanizedTimeDiff,它支持/即将支持多种语言,如果这是您的问题:


这是一个非常好的答案,它将在纪元(1970年1月1日)之后的几秒钟内返回一个格式良好的字符串,如“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"];
}

我想在他们的移动应用程序中使用Facebook那样的日期格式,所以我创建了这个NSDate类别-希望它对某些人有用(这种东西应该放在标准库中!):)


在较新版本的iOS中,自从提出此问题以来,
NSDateFormatter
已添加此功能。现在,它可以使用
doesRelativeDateFormatting
属性执行此操作。

添加到解决方案中,请尝试此更简化的方法

    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];
NSDateComponents*today=[NSCalendar currentCalendar]组件:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:passed toDate:[NSDate date]选项:0];
NSTimeInterval interval=[[NSDate date]timeIntervalSinceDate:date];
如果(间隔<60)timestampString=[NSString stringWithFormat:@“%d秒前”,今天.秒];
如果(间隔<60*60)timestampString=[NSString stringWithFormat:@“%d分钟前”,今天.min];
如果(间隔<60*60*24)timestamsString=[NSString stringWithFormat:@“%d小时前”,今天.hour];
else timestampString=[NSString stringWithFormat:@“%d天前”,今天.day];
此代码将在中显示时间 ------------2秒前的样子 ------------大约2分钟前 ------------两小时前一样 ------------两天前 ------------像两周前一样 ------------像两个月前一样 最后。。。。 两年前
:)试试这个

可能重复的带有示例链接的检查。这是一个很好的小库,仅本地化就值得投票;因为这是其他提议的解决方案所没有的。同意@CarlosP。外观也提供了很多语言。这应该会得到更多的支持,这是一个伟大的开发人员创建的很棒的工具包,而且非常容易使用。我浏览了你的库,它非常有用。但在你的图书馆里,像“刚才”、“6分钟前”、“7小时前”这样的东西很管用。但我也想要“3天前”、“4周前”、“2年前”之类的东西。如何做到这一点?这是为了模仿Facebook风格的日期格式而创建的。它是为了让人可读和容易理解(他们对如何最好地表示日期进行了大量的思考,我认为当您使用它时,这是一种很好的格式,这一点非常清楚。当您查看过去的时间间隔时,像4周前这样的事情并没有为您提供足够的具体信息。如果您想得到类似的内容,只需修改if声明。但这是我公司的要求,而且我认为如果我写“1W”(一周前),它可能会占用大量空间,而不是显示“上午12:42时10月3日”无法使其工作。检查了文档,不确定我做错了什么。如果我将格式设置为常规日期,我会得到一个字符串。但是如果我使用cal SetDoes RelativeDate格式,我不会得到任何回复。想法?代码示例?你可以在使用Google的一些教程中找到它,但我认为你应该将你的问题作为新的SO问题发布,以便我们可以看到你的c颂歌!没有它很难给出建议。
+(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];

}