-4

我如何在 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];
}
4

2 回答 2

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";
        }
    }
于 2012-04-06T11:02:12.550 回答
2

Objective C 代码首先从字符串中解析日期和时间,然后将其转换为易于阅读的“1 天前”。

虽然 Rowland Shaw 的代码很好地解决了第二部分,但它无法解析日期/时间字符串,因为 C# 不支持像“CDT”这样的时区名称。为了解决这个问题,您应该查看https://stackoverflow.com/a/284785/413337ConvertZoneToLocalDifferential中的方法。该方法对日期/时间字符串进行预处理,以便它可以被 C# 解析。

于 2012-04-06T11:07:08.740 回答