我可以使用NSDateComponentsFormatter来获取“一小时前”或“一天前”之类的字符串吗? 我的意思是,我认为应该很容易得到“1小时前”或“1天前”,但不知道。
答案 0 :(得分:1)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *locale = [NSLocale currentLocale];
[dateFormatter setLocale:locale];
[dateFormatter setDoesRelativeDateFormatting:YES];
答案 1 :(得分:1)
您可以使用此功能
- (NSString *)timeAgo
{
NSDate *now = [NSDate date];
double deltaSeconds = fabs([self timeIntervalSinceDate:now]);
double deltaMinutes = deltaSeconds / 60.0f;
int minutes;
if(deltaSeconds < 5)
{
return NSDateTimeAgoLocalizedStrings(@"Just now");
}
else if(deltaSeconds < 60)
{
return [self stringFromFormat:@"%%d %@seconds ago" withValue:deltaSeconds];
}
else if(deltaSeconds < 120)
{
return NSDateTimeAgoLocalizedStrings(@"A minute ago");
}
else if (deltaMinutes < 60)
{
return [self stringFromFormat:@"%%d %@minutes ago" withValue:deltaMinutes];
}
else if (deltaMinutes < 120)
{
return NSDateTimeAgoLocalizedStrings(@"An hour ago");
}
else if (deltaMinutes < (24 * 60))
{
minutes = (int)floor(deltaMinutes/60);
return [self stringFromFormat:@"%%d %@hours ago" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 2))
{
return NSDateTimeAgoLocalizedStrings(@"Yesterday");
}
else if (deltaMinutes < (24 * 60 * 7))
{
minutes = (int)floor(deltaMinutes/(60 * 24));
return [self stringFromFormat:@"%%d %@days ago" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 14))
{
return NSDateTimeAgoLocalizedStrings(@"Last week");
}
else if (deltaMinutes < (24 * 60 * 31))
{
minutes = (int)floor(deltaMinutes/(60 * 24 * 7));
return [self stringFromFormat:@"%%d %@weeks ago" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 61))
{
return NSDateTimeAgoLocalizedStrings(@"Last month");
}
else if (deltaMinutes < (24 * 60 * 365.25))
{
minutes = (int)floor(deltaMinutes/(60 * 24 * 30));
return [self stringFromFormat:@"%%d %@months ago" withValue:minutes];
}
else if (deltaMinutes < (24 * 60 * 731))
{
return NSDateTimeAgoLocalizedStrings(@"Last year");
}
minutes = (int)floor(deltaMinutes/(60 * 24 * 365));
return [self stringFromFormat:@"%%d %@years ago" withValue:minutes];
}
答案 2 :(得分:0)
非常难过,但是在Foundation框架的格式化程序中没有这样的功能。购买即可使用FormattersKit。该套件包含TTTTimeIntervalFormatter
,可让您执行以下操作:
TTTTimeIntervalFormatter *timeIntervalFormatter = [[TTTTimeIntervalFormatter alloc] init];
[timeIntervalFormatter stringForTimeInterval:0]; // "just now"
[timeIntervalFormatter stringForTimeInterval:-100]; // "1 minute ago"