gpt4 book ai didi

iphone - 如何在 Objective-C 中正确格式化该日期?

转载 作者:行者123 更新时间:2023-12-03 17:42:54 25 4
gpt4 key购买 nike

我有以下字符串:

“2011-08-31 14:12:24”

如何格式化它,使其显示为“2 小时前”(如果这是已经过去的时间)?

我有一些代码的工作原理类似,但不完全相同:

+(NSString*)toShortTimeIntervalString:(NSString*)sDate  
{
NSDateFormatter* df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate* date = [df dateFromString:[sDate stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]];
[df release];

NSDate* today = [[NSDate alloc] init];
NSDate *d = date; //[_twitter_dateFormatter dateFromString:sDate];
NSTimeInterval interval = [today timeIntervalSinceDate:d];
[today release];

//TODO: added ABS wrapper
double res = 0;
NSString* result;
if(interval > SECONDS_IN_WEEK)
{
res = fabs(interval / SECONDS_IN_WEEK);
result = [NSString stringWithFormat:@"%1.0fw ago", res];
}
else if(interval > SECONDS_IN_DAY)
{
res = fabs(interval / SECONDS_IN_DAY);
result = [NSString stringWithFormat:@"%1.0fd ago", res];
}
else if (interval > SECONDS_IN_HOUR){
res = fabs(interval / SECONDS_IN_HOUR);
result = [NSString stringWithFormat:@"%1.0fh ago", res];
}
else if (interval > SECONDS_IN_MIN) {
res = fabs(interval / SECONDS_IN_MIN);
result = [NSString stringWithFormat:@"%1.0fm ago", res];
}
else
{
interval = fabs(interval);
result = [NSString stringWithFormat:@"%1.0fs ago", interval];
}
return result;
}

最佳答案

我构建了一个 NSValueTransformer 来执行此操作。您可以查看它以获取有关您自己的代码的提示。 https://github.com/billgarrison/SORelativeDateTransformer

关于iphone - 如何在 Objective-C 中正确格式化该日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7262184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com