[英]DateTime series of Years months weeks and mins ago
我不太清楚我的示例在做什么,但是我需要我的函數返回的是一個像這樣表示的字符串
1yr, 2 months or
1yr or
2months or
2months 2weeks or
3mins ago
如果有人知道該怎么做,請留下答案
private string GetTimeSpan(DateTime creationDate)
{
string timespan = "";
if (Math.Floor(DateTime.Today.Subtract(creationDate).TotalDays / 365.25) >= 1)
{
timespan += ((int)Math.Floor(DateTime.Today.Subtract(creationDate).TotalDays / 365.25)).ToString() + "yr, ";
}
else if (Math.Floor(DateTime.Today.Subtract(creationDate).TotalDays / 365.25) < 1)
{
timespan += ((int)Math.Floor(DateTime.Today.Subtract(creationDate).TotalDays / 365.25)).ToString();
}
return timespan;
}
System.DateTime
具有-
運算符重載 ,它需要兩個DateTime
(因為它是二進制運算符),並返回一個TimeSpan
實例:
TimeSpan span = DateTime.Now - someOtherTime;
那應該給您一個TimeSpan
,它代表兩個DateTime
實例之間的時間。 要打印出所需的字符串,可以通過擴展方法執行以下操作:
public static string Print(this TimeSpan p)
{
var sb = new StringBuilder();
if(p.Days > 365)
sb.AppendFormat("{0}yr, ", p.Years / 365);
if(p.Days % 365 > 30) // hard-code 30 as month interval...
sb.AppendFormat("{0}months, ", ( p.Days % 365 ) /30);
if(p.Days % 365 % 30 > 7)
sb.AppendFormat("{0}weeks, ", p.Days % 365 % 30 / 7);
if(p.Days % 365 % 30 % 7 > 0)
sb.AppendFormat("{0}days, ", p.Days % 365 % 30 % 7);
if(p.Hours > 0)
sb.AppendFormat("{0}hr, ", p.Hours);
// ... and so on ...
sb.Remove(sb.Length - 2, 2); // remove the last ", " part.
return sb.ToString();
}
然后,您將使用它像:
string span = (DateTime.Now - creationDate).Print();
// ----------------------------------------------------------------------
public void DateDiffSample()
{
DateTime date1 = new DateTime( 2009, 11, 8, 7, 13, 59 );
Console.WriteLine( "Date1: {0}", date1 );
// > Date1: 08.11.2009 07:13:59
DateTime date2 = new DateTime( 2011, 3, 20, 19, 55, 28 );
Console.WriteLine( "Date2: {0}", date2 );
// > Date2: 20.03.2011 19:55:28
DateDiff dateDiff = new DateDiff( date1, date2 );
Console.WriteLine( "DateDiff.GetDescription(1): {0}", dateDiff.GetDescription( 1 ) );
// > DateDiff.GetDescription(1): 1 Year
Console.WriteLine( "DateDiff.GetDescription(2): {0}", dateDiff.GetDescription( 2 ) );
// > DateDiff.GetDescription(2): 1 Year 4 Months
Console.WriteLine( "DateDiff.GetDescription(3): {0}", dateDiff.GetDescription( 3 ) );
// > DateDiff.GetDescription(3): 1 Year 4 Months 12 Days
Console.WriteLine( "DateDiff.GetDescription(4): {0}", dateDiff.GetDescription( 4 ) );
// > DateDiff.GetDescription(4): 1 Year 4 Months 12 Days 12 Hours
Console.WriteLine( "DateDiff.GetDescription(5): {0}", dateDiff.GetDescription( 5 ) );
// > DateDiff.GetDescription(5): 1 Year 4 Months 12 Days 12 Hours 41 Mins
Console.WriteLine( "DateDiff.GetDescription(6): {0}", dateDiff.GetDescription( 6 ) );
// > DateDiff.GetDescription(6): 1 Year 4 Months 12 Days 12 Hours 41 Mins 29 Secs
} // DateDiffSample
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.