From 943e25a252d15d07f047bb7d1f8dae38d0d8a89b Mon Sep 17 00:00:00 2001 From: Hylke Bons Date: Sun, 20 Jun 2010 20:42:41 +0100 Subject: [PATCH] Add method ToRelativeDate to SparkleHelpers --- SparkleShare/SparkleHelpers.cs | 57 ++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/SparkleShare/SparkleHelpers.cs b/SparkleShare/SparkleHelpers.cs index c3b6e9e8..134eddd7 100644 --- a/SparkleShare/SparkleHelpers.cs +++ b/SparkleShare/SparkleHelpers.cs @@ -141,6 +141,63 @@ namespace SparkleShare { } + + // Formats a timestamp to a relative date compared to the current time + // Example: "about 5 hours ago" + public static string ToRelativeDate (DateTime date_time) + { + TimeSpan time_span = new TimeSpan (0); + time_span = DateTime.Now - date_time; + + if (time_span <= TimeSpan.FromSeconds (60)) { + if (time_span.Seconds > 1) + return string.Format ("{0} seconds ago", time_span.Seconds); + else + return "a second ago"; + } + + if (time_span <= TimeSpan.FromSeconds (60)) { + if (time_span.Minutes > 1) + return string.Format ("about {0} minutes ago", time_span.Minutes); + else + return "a minute ago"; + } + + if (time_span <= TimeSpan.FromHours(24)) { + if (time_span.Hours > 1) + return string.Format ("about {0} minutes ago", time_span.Hours); + else + return "about an hour ago"; + } + + if (time_span <= TimeSpan.FromDays(30)) { + if (time_span.Days > 1) + return string.Format ("{0} days ago", time_span.Days); + else + return "yesterday"; + } + + if (time_span <= TimeSpan.FromDays(365)) { + if (time_span.Days > 1) + return string.Format ("{0} months ago", (int) time_span.Days / 30); + else + return "a month ago"; + } + + if (time_span <= TimeSpan.FromDays(365)) { + if (time_span.Days > 1) + return string.Format ("{0} months ago", (int) time_span.Days / 365); + else + return "a month ago"; + } + + if (time_span.Days > 365) + return string.Format ("{0} months ago", (int) time_span.Days / 365); + else + return "a year ago"; + + } + } }