This repository was archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathTimeSpanExtensions.cs
89 lines (77 loc) · 3.04 KB
/
TimeSpanExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Globalization;
namespace GitHub.UI.Converters
{
public static class TimeSpanExtensions
{
public static string Humanize(TimeSpan duration, CultureInfo culture, OutputTense outputTense = OutputTense.Past)
{
if (duration.Ticks <= 0)
{
return Resources.JustNow;
}
const int year = 365;
const int month = 30;
const int day = 24;
const int hour = 60;
const int minute = 60;
if (duration.TotalDays >= year)
{
return GetFormattedValue(culture, (int) (duration.TotalDays / year),
outputTense,
Resources.YearsAgo, Resources.Years,
Resources.YearAgo, Resources.Year);
}
if (duration.TotalDays >= 360)
{
return string.Format(culture, outputTense == OutputTense.Past ? Resources.MonthsAgo : Resources.Month, 11);
}
if (duration.TotalDays >= month)
{
return GetFormattedValue(culture, (int)(duration.TotalDays / month),
outputTense,
Resources.MonthsAgo, Resources.Months,
Resources.MonthAgo, Resources.Month);
}
if (duration.TotalHours >= day)
{
return GetFormattedValue(culture, (int)(duration.TotalHours / day),
outputTense,
Resources.DaysAgo, Resources.Days,
Resources.DayAgo, Resources.Day);
}
if (duration.TotalMinutes >= hour)
{
return GetFormattedValue(culture, (int)(duration.TotalMinutes / hour),
outputTense,
Resources.HoursAgo, Resources.Hours,
Resources.HourAgo, Resources.Hour);
}
if (duration.TotalSeconds >= minute)
{
return GetFormattedValue(culture, (int)(duration.TotalSeconds / minute),
outputTense,
Resources.MinutesAgo, Resources.Minutes,
Resources.MinuteAgo, Resources.Minute);
}
return GetFormattedValue(culture, (int) duration.TotalSeconds,
outputTense,
Resources.SecondsAgo, Resources.Seconds,
Resources.SecondAgo, Resources.Second);
}
private static string GetFormattedValue(CultureInfo culture, int value, OutputTense outputTense,
string multiplePast, string multipleCompleted,
string singlePast, string singleCompleted)
{
var formatString = value > 1
? outputTense == OutputTense.Past ? multiplePast : multipleCompleted
: outputTense == OutputTense.Past ? singlePast : singleCompleted;
return string.Format(culture, formatString, value);
}
public enum OutputTense
{
Past,
Completed
}
}
}