private class Treshold { public Treshold(TimeSpan value, string description, Func<TimeSpan, int> converter) { Value = value; Description = description; Converter = converter; } public TimeSpan Value { get; } public string Description { get; } public Func<TimeSpan, int> Converter { get; } } public static string RelativeDateTime(DateTime theDate) => FriendlyTimespan(DateTime.Now - theDate); public static string FriendlyTimespan(TimeSpan t) { var thresholds = new List<Treshold> { new Treshold(TimeSpan.FromMinutes(1), "{0} seconden", x => x.Seconds), new Treshold(TimeSpan.FromMinutes(2), "één minuut ", x => x.Minutes), new Treshold(TimeSpan.FromMinutes(45), "{0} minuten", x => x.Minutes), new Treshold(TimeSpan.FromMinutes(120), "één uur", x => x.Hours), new Treshold(TimeSpan.FromDays(1), "{0} uur", x => x.Hours), new Treshold(TimeSpan.FromDays(2), "gisteren", x => x.Days), new Treshold(TimeSpan.FromDays(30), "{0} dagen", x => x.Days), new Treshold(TimeSpan.FromDays(365), "{0} maanden", x => x.Days / 30), new Treshold(TimeSpan.MaxValue, "{0} jaar", x => x.Days / 365) }; var threshold = thresholds.OrderBy(x => x.Value).FirstOrDefault(x => x.Value > t) ?? thresholds.Last(); return string.Format(threshold.Description, threshold.Converter(t)); }
429100cookie-checkC# calculate / display relative time