我如何在wp7
中移植这组代码-(NSString *) timeSincePosted:(NSString *)ad_date {
if (!ad_date || ([ad_date compare:@""] == NSOrderedSame) || ([ad_date rangeOfString:@"-"].location == NSNotFound))
return @"";
// date format
//2010-04-22, 5:27PM EDT
NSDateFormatter *dateFormatter_CL = [[[NSDateFormatter alloc] init] autorelease];
NSLocale *enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
[dateFormatter_CL setLocale:enUSPOSIXLocale];
[dateFormatter_CL setDateFormat:@"yyyy-MM-dd, h:mma zzz"];
NSDate *CL_adDate = [dateFormatter_CL dateFromString: ad_date];
// Time since now
NSTimeInterval deltaT = -[CL_adDate timeIntervalSinceNow];
int deltaMin = deltaT/60;
int deltaHr = deltaMin/60;
int deltaDay = deltaHr/24;
if (deltaMin < 1) return [NSString stringWithString:@"0 mins"];
if (deltaMin == 1) return [NSString stringWithString:@"1 min"];
if (deltaMin < 60) return [NSString stringWithFormat:@"%d mins", deltaMin];
if (deltaHr <= 1) return [NSString stringWithString:@"1 hr"];
if (deltaHr < 24) return [NSString stringWithFormat:@"%d hrs", deltaHr];
if (deltaDay < 2) return [NSString stringWithString:@"1 day ago"];
return [NSString stringWithFormat:@"%d days ago", deltaDay];
}
答案 0 :(得分:3)
我在这里通过电线飞行,但我想你想要的东西:
/// <summary>
/// Returns a string approximation of the time since the specified time.
/// </summary>
/// <param name="adDate">The ad date.</param>
/// <returns></returns>
public static string TimeSincePosted(string adDate)
{
return TimeSincePosted(DateTime.ParseExact(adDate, "\D\a\t\e: yyyy-MM-dd, hh:mmtt K", CultureInfo.CurrentUICulture));
}
/// <summary>
/// Returns a string approximation of the time since the specified time.
/// </summary>
/// <param name="adDate">The ad date.</param>
/// <returns></returns>
public static string TimeSincePosted(DateTime adDate)
{
TimeSpan delta = DateTime.Now - adDate;
if( delta.TotalDays > 1 )
{
return string.Format("{0} days ago", delta.TotalDays);
}
else if( delta.TotalDays == 1)
{
return "1 day ago";
}
else if( delta.TotalHours > 1)
{
return string.Format("{0} hrs", delta.TotalHours);
}
else if( delta.TotalHours == 1)
{
return "1 hr";
}
else if( delta.TotalMinutes > 1)
{
return string.Format("{0} mins", delta.TotalMinutes);
}
else if( delta.TotalMinutes == 1)
{
return "1 min";
}
else
{
return "0 mins";
}
}
答案 1 :(得分:2)
Objective C代码首先从字符串中解析日期和时间,然后将其转换为类似“1天前”的易读性。
虽然Rowland Shaw的代码很好地解决了第二部分,但它无法解析日期/时间字符串,因为C#不支持像“CDT”这样的时区名称。为了解决这个问题,您应该查看https://stackoverflow.com/a/284785/413337中的方法ConvertZoneToLocalDifferential
。该方法预处理日期/时间字符串,因此可以通过C#进行解析。