我想把nsdate转换成相对格式,比如"Today","Yesterday","a week ago","a month ago","a year ago","date as it is".

我为它写了以下方法..但也有人说它只是按日期打印..你能告诉我出了什么问题吗?

//下面是我的函数,它将日期转换为相对字符串

+(NSString *)getDateDiffrence:(NSDate *)strDate{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];

    df.timeStyle = NSDateFormatterMediumStyle;
    df.dateStyle = NSDateFormatterShortStyle;
    df.doesRelativeDateFormatting = YES;
    NSLog(@"STRING DATEEE : %@ REAL DATE TODAY %@",[df stringFromDate:strDate],[NSDate date]);
      return [df stringFromDate:strDate];

}

我有以下格式的日期字符串"2013-10-29T09:38:00"

当我试图给NSDate对象赋值时,它总是返回空日期

如何解决这个问题?

//下面是我调用上述函数的代码

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [formatter dateFromString:[threadDict objectForKey:@"lastMessageDate"]];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZZZZ"];

NSString *date1 = [formatter stringFromDate:date];
NSDate *date_d = [formatter dateFromString:date1];
NSString *resultstr=[UserManager getDateDiffrence:date];

self.dateLabel.text=resultstr;

推荐答案

For simplicity I'm assuming that the dates you are formatting are all in the past (no "tomorrow" or "next week"). It's not that it can't be done but it would be more cases to deal with and more strings to return.


你可以将components:fromDate:toDate:options:与你想要的任何日期组件组合使用,以获得两个日期之间的年数、月数、周数、日数、小时数等.然后按照从最重要(例如年)到最不重要(例如天)的顺序遍历它们,您可以仅基于最重要的部分来设置字符串的格式.

例如:1周、2天和7小时前的日期将被格式化为"1周".

如果要为单位的特殊编号创建特殊字符串,如"1天前"的"明天",则可以在确定该分量是最重要的分量后判断该分量的值.

代码如下所示:

- (NSString *)relativeDateStringForDate:(NSDate *)date
{
    NSCalendarUnit units = NSCalendarUnitDay | NSCalendarUnitWeekOfYear | 
                           NSCalendarUnitMonth | NSCalendarUnitYear;

    // if `date` is before "now" (i.e. in the past) then the components will be positive
    NSDateComponents *components = [[NSCalendar currentCalendar] components:units
                                                                   fromDate:date
                                                                     toDate:[NSDate date]
                                                                    options:0];

    if (components.year > 0) {
        return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
    } else if (components.month > 0) {
        return [NSString stringWithFormat:@"%ld months ago", (long)components.month];
    } else if (components.weekOfYear > 0) {
        return [NSString stringWithFormat:@"%ld weeks ago", (long)components.weekOfYear];
    } else if (components.day > 0) {
        if (components.day > 1) {
            return [NSString stringWithFormat:@"%ld days ago", (long)components.day];
        } else {
            return @"Yesterday";
        }
    } else {
        return @"Today";
    }
}

如果日期也可能在future ,则可以按相同顺序判断组件的绝对值,然后判断其是否为正或负,以返回相应的字符串.我只展示以下年份:

if ( abs(components.year > 0) ) { 
    // year is most significant component
    if (components.year > 0) {
        // in the past
        return [NSString stringWithFormat:@"%ld years ago", (long)components.year];
    } else {
        // in the future
        return [NSString stringWithFormat:@"In %ld years", (long)components.year];
    }
} 

Objective-c相关问答推荐

从 C# 到 Objective C 会有多大的飞跃

将 CSS 插入 UIWebView / WKWebView 中加载的 HTML

如何使用 Cocoa 创建临时文件?

如何以编程方式暂停 NSTimer?

Objective-C (cocoa) 等价于python的endswith/beginswith

didReceiveRemoteNotification:当应用程序处于后台并且未连接到Xcode时未调用fetchCompletionHandler

如何以编程方式退出 mac 应用程序?

在 ObjC 实现文件中声明的实例变量

如何从 RGBA 创建 UIColor?

了解按位与运算符

dyld:找不到符号:try 运行 iOS 应用程序时的 _NSURLAuthenticationMethodClientCertificate

Select 时 UITableViewCell 复选标记更改

Modal segue,导航栏消失

我可以在 Objective-C 中重载运算符吗?

iPhone - dequeueReusableCellWithIdentifier 用法

将自定义子视图(在 xib 中创建)添加到视图控制器的视图 - 我在做什么错

AVAudioPlayer 不播放任何声音

如何检测父视图控制器中模态视图控制器的解除?

UIPageViewController,如何在不打乱数据源指定顺序的情况下正确跳转到特定页面?

在 iOS 8 中使用 NSMutableAttributedString 的字符串的下划线部分不起作用