The largest value for a .NET
TimeSpan
is the duration in Days. This sample uses the
Time Period Library for .NET[
^] to represent a
TimeSpan
in Months and Years.
An important aspect is the referring date of the
TimeSpan
. Because Months contain varying number of days, the same duration produces - depending to the referring date - different target dates.
The next snippet redirects a
TimeSpan
into two
DateTime
and returns an user friendly duration using
DateDiff.GetDescription
:
public string GetTimeSpanDescription( TimeSpan timeSpan, int precision = int.MaxValue )
{
return GetTimeSpanDescription( DateTime.Now, timeSpan, precision );
}
public string GetTimeSpanDescription( DateTime moment, TimeSpan timeSpan, int precision = int.MaxValue )
{
if ( timeSpan == TimeSpan.Zero )
{
return string.Empty;
}
bool isPositive = timeSpan > TimeSpan.Zero;
DateTime date1 = isPositive ? moment : moment.Subtract( timeSpan );
DateTime date2 = isPositive ? moment.Add( timeSpan ) : moment;
return new DateDiff( date1, date2 ).GetDescription( precision );
}
And now some samples:
public void UserFriendlyTimeSpanSample()
{
TimeSpan lastVisit = new TimeSpan( 400, 7, 25, 0 );
Console.WriteLine( "last visit before {0}",
GetTimeSpanDescription( lastVisit, 3 ) );
TimeSpan reminderDuration = new TimeSpan( 60, 0, 0, 0, 0 );
Console.WriteLine( "reminder duration: {0} Days", reminderDuration.TotalDays );
DateTime now = DateTime.Now;
DateTime moment1 = new DateTime( 2011, 4, 1 );
DateTime moment2 = new DateTime( 2011, 2, 1 );
DateTime moment3 = new DateTime( 2011, 3, 1 );
Console.WriteLine( "last reminder (from now): {0}",
GetTimeSpanDescription( now, reminderDuration.Negate() ) );
Console.WriteLine( "last reminder ({0:d}): {1}", moment1,
GetTimeSpanDescription( moment1, reminderDuration.Negate() ) );
Console.WriteLine( "last reminder ({0:d}): {1}", moment2,
GetTimeSpanDescription( moment2, reminderDuration.Negate() ) );
Console.WriteLine( "last reminder ({0:d}): {1}", moment3,
GetTimeSpanDescription( moment3, reminderDuration.Negate() ) );
Console.WriteLine( "next reminder (from now): {0}",
GetTimeSpanDescription( now, reminderDuration ) );
Console.WriteLine( "next reminder {0:d}: {1}", moment1,
GetTimeSpanDescription( moment1, reminderDuration ) );
Console.WriteLine( "next reminder {0:d}: {1}", moment2,
GetTimeSpanDescription( moment2, reminderDuration ) );
Console.WriteLine( "next reminder {0:d}: {1}", moment3,
GetTimeSpanDescription( moment3, reminderDuration ) );
}