forked from MenaceSan/DotStd
/
DateUtil.cs
368 lines (322 loc) · 11.9 KB
/
DateUtil.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
using System;
using System.Threading.Tasks;
namespace DotStd
{
public enum MonthId : byte
{
// Month of the year.
// Oddly .NET System doesn't define months.
// like Microsoft.VisualBasic.MonthName
// Use cultural description from DateTime.ToString("MMM", CultureInfo.InvariantCulture)
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12
};
public static class DateUtil
{
// Utility for date and time.
// System.DayOfWeek (same as Javascript) = Sunday is 0, Monday is 1,
// NOTE: DayOfWeek is different for MSSQL and MySQL db time functions.
public static readonly DateTime kExtremeMin = new DateTime(1800, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); // reasonably inclusive min date that can be held by most db's. BUT NOT MS SQL smalldate
// public static readonly DateTime kExtremeMin2 = new DateTime(1800, 1, 1); // MySQL doesn't like the UTC stuff ?? null !!! "Unable to cast object of type 'System.String' to type 'System.DateTime'."
public static readonly DateTime kUnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); // JavaScript epoch.
public static readonly DateTime kExtremeMax = new DateTime(2179, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc); // reasonably inclusive max date that can be held by most db's.
public const int kHoursInWeek = 168; // (7*24)
public const int kMinutesInDay = 3600; // 24*60 // Modulus for day time.
public const string kShortDate = "yyyy-MM-dd"; // default short data format ALA JavaScript, ISO Date. NOT ToShortDateString()/ToString("d") which are cultural.
public const string kShortDate2 = "MM/dd/yyyy"; // Weird format to be avoided.
public static bool IsExtremeDate(DateTime dt)
{
// Is this probably a useless date? NOTE: DateTime is not nullable so use this as null.
// e.g. Year <= 1
return dt <= kExtremeMin || dt >= kExtremeMax;
}
public static bool IsExtremeDate(DateTime? dt)
{
if (dt == null)
return true;
return IsExtremeDate(dt.Value);
}
public static double ToJavaTime(DateTime dt)
{
// JavaScript time stamp is milliseconds past kUnixEpoch
if (IsExtremeDate(dt))
return 0;
return (dt - kUnixEpoch).TotalMilliseconds;
}
public static DateTime FromJavaTime(double javaTimeStamp)
{
// JavaScript time stamp is milliseconds past epoch. NOT seconds like Unix time.
// Return UTC time.
return kUnixEpoch.AddMilliseconds(javaTimeStamp);
}
public static string TimeSpanStr2(TimeSpan ts, out string arg)
{
// a translatable approximate span.
// get a string for a rough amount of time ago or ahead.
// var ts = (yourDate - TimeNow.Utc);
const int kSECOND = 1;
const int kMINUTE = 60 * kSECOND;
const int kHOUR = 60 * kMINUTE;
const int kDAY = 24 * kHOUR;
const int kMONTH = 30 * kDAY; // approximate.
long deltaSec = (long)ts.TotalSeconds;
bool inPast = deltaSec < 0;
string ago = "";
if (inPast)
{
deltaSec = -deltaSec;
ts = new TimeSpan(-ts.Ticks);
ago = " ago";
}
if (deltaSec < 1)
{
arg = null;
return "now";
}
if (deltaSec < kMINUTE)
{
if (deltaSec == 1)
{
arg = null;
return "one second" + ago;
}
arg = deltaSec.ToString();
return "{0} seconds" + ago;
}
if (deltaSec < 2 * kMINUTE)
{
arg = null;
return "a minute" + ago;
}
if (deltaSec < 45 * kMINUTE)
{
arg = (deltaSec / kMINUTE).ToString();
return "{0} minutes" + ago;
}
if (deltaSec < 90 * kMINUTE)
{
arg = null;
return "an hour" + ago;
}
if (deltaSec < 24 * kHOUR)
{
arg = (deltaSec / kHOUR).ToString();
return "{0} hours" + ago;
}
if (deltaSec < 48 * kHOUR)
{
arg = null;
return inPast ? "yesterday" : "tomorrow";
}
if (deltaSec < 30 * kDAY)
{
arg = (deltaSec / kDAY).ToString();
return "{0} days" + ago;
}
if (deltaSec < 12 * kMONTH) // approximate.
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
if (months <= 1)
{
arg = null;
return "one month" + ago;
}
arg = months.ToString();
return "{0} months" + ago;
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); // approximate.
if (years > 200)
{
arg = null;
return "never";
}
if (years <= 1)
{
arg = null;
return "one year" + ago;
}
arg = years.ToString();
return "{0} years" + ago;
}
public static string TimeSpanStr(TimeSpan ts)
{
string arg;
string txt = TimeSpanStr2(ts, out arg);
if (arg == null)
return txt;
return string.Format(txt, arg);
}
public static async Task<string> TimeSpanStrAsync(TimeSpan ts, ITranslatorProvider1 trans)
{
// a translated time span
string arg;
string txt = await trans.TranslateAsync(TimeSpanStr2(ts, out arg));
if (arg == null)
return txt;
return string.Format(txt, arg);
}
public static string TimeMsecStr(long mSec)
{
// How much time in mSec.
// the code that you want to measure comes here
// var watch = System.Diagnostics.Stopwatch.StartNew(); STUFF(); watch.Stop(); TimeUtil.TimeMsecStr(watch.ElapsedMilliseconds);
if (mSec < 1000)
{
return mSec.ToString() + " ms";
}
return (((decimal)mSec) / 1000m).ToString() + " s";
}
public static DayOfWeek ModDOW(DayOfWeek dow)
{
// modulus/wrap to force into valid range. 0 to 6 day of week.
int d = (int)dow;
if (d > 6)
{
d %= 7;
}
else if (d < 0)
{
d %= 7;
d += 7;
}
return (System.DayOfWeek)d;
}
public static DateTime GetDateOfWeekDayPrev(DateTime dt, DayOfWeek dow)
{
// Get DateTime for previous dow (day of week) inclusive of current day.
// Related to similar to cultureInfo.DateTimeFormat.FirstDayOfWeek
int diff = dt.DayOfWeek - dow;
if (diff < 0) // DayOfWeek.Sunday = 0
{
diff += 7;
}
// ASSERT( diff >= 0 );
return dt.Date.AddDays(-diff); // go back. always 0 or negative.
}
public static DateTime GetDateOfWeekDayPrevX(DateTime dt, DayOfWeek dow)
{
// Get previous dow (day of week) NOT including dt.
return GetDateOfWeekDayPrev(dt.AddDays(-1), dow);
}
public static DateTime GetDateOfWeekDayNext(DateTime dt, DayOfWeek dow)
{
// Get DateTime for next dow (day of week) inclusive of current day.
// like GetDateOfWeekDayPrev but get next week.
// Related to similar to cultureInfo.DateTimeFormat.FirstDayOfWeek
int diff = dow - dt.DayOfWeek;
if (diff < 0) // DayOfWeek.Sunday = 0
{
diff += 7;
}
// ASSERT( diff >= 0 );
return dt.Date.AddDays(diff); // go forward.
}
public static DayOfWeek GetDOW(string s) // NOT USED
{
// Get DoW from English string as Enum.
if (s != null)
{
switch (s.ToLower())
{
case "sunday":
case "sun":
case "su":
return DayOfWeek.Sunday;
case "monday":
case "mon":
case "m":
return DayOfWeek.Monday;
case "tuesday":
case "tues":
case "tue":
case "t":
return DayOfWeek.Tuesday;
case "wednesday":
case "wed":
case "w":
return DayOfWeek.Wednesday;
case "thursday":
case "thurs":
case "thu":
case "th":
return DayOfWeek.Thursday;
case "friday":
case "fri":
case "f":
return DayOfWeek.Friday;
case "saturday":
case "sat":
case "sa":
return DayOfWeek.Saturday;
}
}
return DayOfWeek.Monday; // no idea. -1 ?
}
public static int GetTimeMinutes(string s)
{
// Convert a string in format "10:45" to minutes in the day.
// Assume military time if no AM, PM
string[] parts = s.Split(':');
if (parts.Length == 0)
return -1;
int minutes = 0;
int hours = Converter.ToInt(parts[0]);
if (parts.Length > 1)
{
minutes = Converter.ToIntSloppy(parts[1]);
}
if (s.EndsWith("AM") || s.EndsWith("am"))
{
if (hours == 12)
hours = 0; // midnight.
}
else if (s.EndsWith("PM") || s.EndsWith("pm"))
{
if (hours < 12)
hours += 12; // after noon.
}
else if (parts.Length == 1)
{
minutes = hours;
hours = 0;
}
return hours * 60 + minutes;
}
public static string GetTimeStr(int minutes, bool ampm = false, bool space = true)
{
// Convert (0 based) minutes in the day to a military (or AM/PM) time string.
// if (minutes > DateUtil.kMinutesInDay) then just wrap.
if (minutes < 0)
return null;
int hours = (minutes / 60) % 24;
minutes %= 60;
if (ampm)
{
ampm = hours < 12;
hours %= 12;
if (hours == 0)
hours = 12;
return string.Format("{0:D2}:{1:D2}{2}{3}", hours, minutes, space ? " " : "", ampm ? "AM" : "PM");
}
else
{
// ignore hours > 24? or hours %= 24;
return string.Format("{0:D2}:{1:D2}", hours, minutes);
}
}
public static string GetTimeStr(TimeSpan ts, bool ampm = false, bool space = true)
{
return GetTimeStr((int)ts.TotalMinutes, ampm, space);
}
}
}