如何将NSDate转换为相对格式为“今天”,“昨天”,“一周前”,“一个月前”,“一年前”? [英] How to convert NSDate in to relative format as "Today","Yesterday","a week ago","a month ago","a year ago"?

查看:162
本文介绍了如何将NSDate转换为相对格式为“今天”,“昨天”,“一周前”,“一个月前”,“一年前”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将nsdate转换为相对格式,例如今天,昨天,一周前,一个月前,一年前,日期不确定

I want to convert nsdate in to relative format like "Today","Yesterday","a week ago","a month ago","a year ago","date as it is".

我已经为它写了以下方法..但有些如何只是打印,因为它是日期..你能不能告诉我应该是什么问题?

I have written following method for it.. but some how its just printing as it is date.. can you please tell me what should be the problem?

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

//Following is my function which converts the date into relative string

+(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

I have date string with the following format "2013-10-29T09:38:00"

当我尝试提供NSDate对象时,它总是返回null null 。$
所以我试着将那个日期转换为 yyyy-MM-dd HH:mm:ssZZZZ 然后我将这个日期传递给函数然后它只是打印整个日期..

When I tried to give the NSDate object then its always return me null date.
so I tried to convert that date in to yyyy-MM-dd HH:mm:ssZZZZ then I pass this date to function then it's just printing whole date..

如何解决这个问题?

//以下是我称之为的代码上面的函数

//Following is the code I call the above function

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;


推荐答案

为简单起见,我假设您正在格式化的日期都是过去的(没有明天或下周)。这并不是说它无法完成,但处理更多的情况和返回更多的字符串。

您可以使用组件:fromDate:toDate:options:以及您要查找的日期组件的任意组合,以获取年,月,周,天的数量,两个日期之间的小时等。然后按照从最重要(例如年份)到最不重要(例如日)的顺序浏览它们,您可以仅根据最重要的组件格式化字符串。

You can use components:fromDate:toDate:options: with whatever combination of date components you are looking for to get the number of years, months, weeks, days, hours, etc. between two dates. By then going though them in order from most significant (e.g. year) to least significant (e.g. day), you can format a string based only on the most significant component.

例如:1周,2天和7小时前的日期格式为1周。

For example: a date that is 1 week, 2 days and 7 hours ago would be formatted as "1 week".

如果要为特殊字符串创建特殊字符串一个单位的数量,如1天前的明天,那么你可以在确定它是最重要的组成部分后检查该组件的价值。

If you want to create special strings for a special number of a unit, like "tomorrow" for "1 day ago" then you can check the value of that component after you have determined that it is the most significant component.

代码看起来像这样:

- (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";
    }
}






如果您的日期也可以在将来,那么您可以按相同的顺序检查组件的绝对值,然后检查它是正还是负以返回相应的字符串。我只显示以下年份:


If your dates could also be in the future then you can check the absolute value of the components in the same order and then check if it's positive or negative to return the appropriate strings. I'me only showing the year below:

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];
    }
} 

这篇关于如何将NSDate转换为相对格式为“今天”,“昨天”,“一周前”,“一个月前”,“一年前”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆