如何在Windows Phone中实现此功能

本文关键字:实现 功能 Phone Windows | 更新日期: 2023-09-27 18:30:07

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

如何在Windows Phone中实现此功能

我在这里有点绕线飞行,但我想你想要这样的东西:

    /// <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";
        }
    }

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

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