我想将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对象时,它总是返回空日期。
所以我尝试将该日期转换为,yyyy-MM-dd HH:mm:ssZZZZ
然后将此日期传递给函数,然后仅打印整个日期。
如何解决这个问题呢?
//下面是我调用上面函数的代码
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;
为简单起见,我假设您格式化的日期都是过去的日期(没有“明天”或“下周”)。不是说它不能完成,而是要处理更多的情况,并返回更多的字符串。
您可以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";
}
}
如果您的日期也可能是将来的日期,则可以按相同的顺序检查组件的绝对值,然后检查返回的正确字符串是正还是负。我只显示以下年份:
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];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句