-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.cs
130 lines (116 loc) · 4.05 KB
/
Util.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AlarmApp
{
public class Util
{
public static async Task RunInBackground(TimeSpan timeSpan, Action action)
{
PeriodicTimer? periodicTimer = new(timeSpan);
while (await periodicTimer.WaitForNextTickAsync())
{
action();
}
}
public static bool AreDigitsOnly(string text)
{
return text.All(c => c >= '0' && c <= '9' || c == ':');
}
public static string ConvertDateToRelative(DateTime time)
{
StringBuilder sb = new("");
string suffix = "from now";
TimeSpan timeSpan = new(Math.Abs(DateTime.Now.Subtract(time).Ticks));
TimeSpan span = new(Math.Abs(TimeSpan.FromTicks(timeSpan.Ticks).Ticks));
if (timeSpan.Days > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Days, (timeSpan.Days > 1) ? "days" : "day");
if (timeSpan.Hours <= 0 && timeSpan.Minutes <= 0 && timeSpan.Seconds <= span.Seconds)
{
}
else
{
sb.Append(", ");
}
}
if (timeSpan.Hours > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
if (timeSpan.Minutes > 0 || timeSpan.Seconds > 0)
{
sb.Append(", ");
}
}
if (timeSpan.Minutes > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
if (timeSpan.Seconds > 0)
{
sb.Append(", ");
}
}
if (timeSpan.Seconds > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds " : "second ");
}
sb.Append(suffix);
return sb.ToString();
}
public static DateTime ConvertStringToTime(string time, Times timeType)
{
DateTime until = DateTime.Now;
bool first = true;
int number = 0;
foreach (string s in time.Split(':'))
{
if (first)
{
switch (timeType)
{
case Times.Seconds:
until = until.AddSeconds(int.Parse(s));
break;
case Times.Minutes:
until = until.AddMinutes(int.Parse(s));
break;
case Times.Hours:
until = until.AddHours(int.Parse(s));
break;
case Times.Days:
until = until.AddHours(int.Parse(s));
break;
default:
break;
}
first = false;
number++;
}
else
{
switch (timeType - number)
{
case Times.Seconds:
until = until.AddSeconds(int.Parse(s));
break;
case Times.Minutes:
until = until.AddMinutes(int.Parse(s));
break;
case Times.Hours:
until = until.AddHours(int.Parse(s));
break;
case Times.Days:
until = until.AddHours(int.Parse(s));
break;
default:
break;
}
number++;
}
}
return until;
}
}
}