-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathLightCore.Time.pas
More file actions
486 lines (363 loc) · 15.2 KB
/
LightCore.Time.pas
File metadata and controls
486 lines (363 loc) · 15.2 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
UNIT LightCore.Time;
{=============================================================================================================
www.GabrielMoraru.com
2026.01.30
Github.com/GabrielOnDelphi/Delphi-LightSaber/blob/main/System/Copyright.txt
--------------------------------------------------------------------------------------------------------------
DateTime utilities
For I/O (disk, files) related functions see the "Time" section in LightCore.IO:
function ExtractTimeFromFileName
function DateToStr_IO
function TimeToStr_IO
function DateTimeToStr_IO
function DateTimeToStr_IO
=============================================================================================================}
INTERFACE
USES
System.SysUtils, System.TimeSpan, System.DateUtils;
// CURRENT DATE-TIME
function TodayIs: string; { Returns today as date based on Locale. Example: Montag }
function CurrentDateToString{(ShowSeconds: Boolean)}: string; { Returns today as date & time. Example: 31.12.2021 - 16:50 }
function CurrentTimeToString(ShowSeconds: Boolean): string; { Returns time in short format (no seconds). Example: 16:50 }
function TimeToString(CONST T: TDateTime; ShowSeconds: Boolean): string;
function CurrentYear: Word;
function CurrentMonth: Word;
function CurrentDay: Word;
function CurrentHour: Word;
// DECODE
function DecodeHour (Time: TTime): Word;
function DecodeMinute (Time: TTime): Word;
function DecodeSecond (Time: TTime): Word;
// FORMAT
function GetUniversalDateFormat: TFormatSettings;
// COMPARISON
function SameDateEx (Time1, Time2: TDateTime): boolean; deprecated 'Use System.DateUtils.SameDate instead';
function EarlierThan (Date1, Date2: TDateTime): boolean; { Returns true if Date1 is smaller (earlier) than Date2 }
function DaysBetweenEx (CONST MilestoneDate, CurrentDate: TDateTime): Double; deprecated 'Use System.DateUtils.DaySpan instead';
function NewDaysBetween (CONST MilestoneDate, CurrentDate: TdateTime): Double;
function SecondsBetweenEx (CONST MilestoneDate, CurrentDate: TDateTime): Int64; { Returns the number of seconds between two specified TDateTime values. The difference between this function and the Embarcadero one is that it returns zero if CurrentDate >= MilestoneDate }
function DateIsToday (Year, Month, Day: word): Boolean; { Returns true if the specified date is today }
// STRING CONVERSIONS
function StringToSeconds (CONST s: String): Integer; { Converts a string formated like 'hh:mm:ss' to seconds. }
function StringIsDate (CONST s: string): Boolean;
function StringIsTime (CONST s: string): Boolean;
function DateToStrUS (CONST Time: TDateTime): string; { converts date to string, using the US (YYY.MM.DD) format }
// CONVERSIONS
procedure SecondsToTime (Seconds : Cardinal; VAR D, H, M, S: Cardinal);
function MiliSecToTimeAuto (MSeconds: Cardinal): string;
function mSecondsToTime (mSeconds: Cardinal): string;
function ShowTimeNice (Seconds: Cardinal): string; overload;
function ShowTimeNice (Seconds: Integer): string; overload; { Prevents Delphi from resolving Integer to the TDateTime overload }
function ShowTimeNice (Seconds: Int64): string; overload; { Prevents Delphi from resolving Int64 to the TDateTime overload }
function ShowTimeNice (aTime: TDateTime): string; overload;
function DateTimeToMilliseconds(aDateTime: TDateTime): Int64;
function DateToTime_ (aDate : TDateTime): string;
// CONVERSIONS
function Date2Cardinal (xDate: TDate): Cardinal;
function Cardinal2Date (xCardinal: Cardinal): TDate;
IMPLEMENTATION
USES LightCore;
function mSecondsToTime(mSeconds: Cardinal): string;
begin
Result:= ShowTimeNice(mSeconds DIV 1000);
end;
function DateToTime_(aDate: TDateTime): string;
VAR
Days: Integer;
Hour, Min, Sec, MSec: Word;
begin
Days:= Trunc(aDate);
DecodeTime(aDate, Hour, Min, Sec, MSec);
Result:= Format('%d:%.2d:%.2d:%.2d', [Days, Hour, Min, Sec]);
end;
procedure SecondsToTime (Seconds: Cardinal; VAR D, H, M, S: Cardinal);
begin
D := (Seconds DIV SecsPerDay);
H := (Seconds DIV SecsPerHour) - (D* 24);
M := (Seconds DIV SecsPerMin) - (D* 24* SecsPerMin) - (H* 60);
S := Seconds - (D* SecsPerday) - (H* 3600)- (M*60);
end;
{ Common function that does the actual formatting }
function ShowTimeNiceCommon(D, H, M, S: Cardinal): string;
begin
Result := '';
{ Show days }
if D > 0 then Result := IntToStr(D) + ' days ';
{ Show hours }
if H > 0 then Result := Result + IntToStr(H) + 'h ';
{ Show minutes but ONLY if we have less than 7 days }
if D <= 7 then
begin
Result := Result + IntToStr(M) + 'm ';
{ Show seconds ONLY if the time is short (under 1h) }
if (D = 0) AND (H = 0)
then Result := Result + IntToStr(S) + 's';
end;
end;
{ Converts seconds to time, but showing the shortest string possible.
For example: it will convert 59 to '59s' and 61 to '1m 01s' }
function ShowTimeNice(Seconds: Cardinal): string; // Old name: SecondsToTime_FormatAuto
var D, H, M, S: Cardinal;
begin
D := (Seconds DIV SecsPerDay);
H := (Seconds DIV SecsPerHour) - (D * 24);
M := (Seconds DIV SecsPerMin) - (D * 24 * SecsPerMin) - (H * 60);
S := Seconds - (D * SecsPerDay) - (H * 3600) - (M * 60);
Result := ShowTimeNiceCommon(D, H, M, S);
end;
{ Overload for Integer arguments.
Without this, Delphi resolves Integer to the TDateTime (Double) overload,
which interprets the value as days instead of seconds. }
function ShowTimeNice(Seconds: Integer): string;
begin
Assert(Seconds >= 0, 'ShowTimeNice: Negative seconds not supported');
Result:= ShowTimeNice(Cardinal(Seconds));
end;
{ Overload for Int64 arguments (e.g., RCertificate.TimeLeft).
Without this, Delphi resolves Int64 to the TDateTime (Double) overload. }
function ShowTimeNice(Seconds: Int64): string;
begin
Assert(Seconds >= 0, 'ShowTimeNice: Negative seconds not supported');
Result:= ShowTimeNice(Cardinal(Seconds));
end;
{ Example 5 days, 23h:59m:59s }
function ShowTimeNice(aTime: TDateTime): string;
var D: Integer;
H, M, S: Word;
begin
D := Trunc(aTime);
H := HourOf(aTime);
M := MinuteOf(aTime);
S := SecondOf(aTime);
Result:= ShowTimeNiceCommon(D, H, M, S);
end;
function MiliSecToTimeAuto(MSeconds: Cardinal): string; //old name: mSecondsToTime
begin
if MSeconds< 1000 { under 1 sec }
then Result:= IntToStr(MSeconds)+ 'ms'
else
if MSeconds< 60000 { under 1 minute }
then Result:= Real2Str(MSeconds / 1000, 3)+ 'sec'
else Result:= ShowTimeNice(MSeconds DIV 1000);
end;
function DateToStrUS(CONST Time: TDateTime): string; { converts date to string, using the US (YYY.MM.DD) format }
VAR aYear, aMonth, aDay : Word;
begin
DecodeDate(Time, aYear, aMonth, aDay);
Result:= IntToStr(aYear)+ '.';
if aMonth < 10
then Result:= Result+ '0'+IntToStr(aMonth)+ '.'
else Result:= Result+ IntToStr(aMonth)+ '.';
if aDay < 10
then Result:= Result+ '0'+IntToStr(aDay)
else Result:= Result+ IntToStr(aDay);
end;
{ Compares two TDateTime values by decoding all components (including milliseconds).
Note: Despite the name 'SameDateEx', this actually compares the FULL datetime including time.
For date-only comparison, use System.DateUtils.SameDate instead.
We cannot compare two TDateTimes directly in Delphi because of floating-point precision.
See: stackoverflow.com/questions/38705011/odd-behavior-when-comparing-two-tdatetime-vars }
function SameDateEx(Time1, Time2: TDateTime): boolean;
VAR
Year1, Month1, Day1, Hour1, Min1, Sec1, Msec1: Word;
Year2, Month2, Day2, Hour2, Min2, Sec2, Msec2: Word;
begin
DecodeDateTime(Time1, Year1, Month1, Day1, Hour1, Min1, Sec1, Msec1);
DecodeDateTime(Time2, Year2, Month2, Day2, Hour2, Min2, Sec2, Msec2);
Result:= (Year1 = Year2) AND (Month1 = Month2) AND (Day1 = Day2) AND (Hour1 = Hour2) AND (Min1 = Min2) AND (Sec1 = Sec2) AND (Msec1 = Msec2);
end;
function EarlierThan(Date1, Date2: TDateTime): boolean; { Returns true if Date1 is smaller (earlier) than Date2 }
begin
Result:= System.DateUtils.CompareDateTime(Date1, Date2) = -1;
end;
function DecodeHour(Time: TTime): Word;
VAR wMin, wSec, wMsec: word;
begin
DecodeTime(Time, Result, wMin, wSec, wMsec);
end;
function DecodeMinute(Time: TTime): Word;
VAR wHor, wSec, wMsec: word;
begin
DecodeTime(Time, wHor, Result, wSec, wMsec);
end;
function DecodeSecond(Time: TTime): Word;
VAR wHor, wMin, wMsec: word;
begin
DecodeTime(Time, wHor, wMin, Result, wMsec);
end;
{ Returns ISO 8601 compatible format settings (YYYY-MM-DD).
Useful for locale-independent date serialization. }
function GetUniversalDateFormat: TFormatSettings;
begin
Result:= TFormatSettings.Create;
Result.DateSeparator:= '-';
Result.TimeSeparator:= ':';
Result.ShortDateFormat:= 'YYYY-MM-DD';
end;
{ Converts a string formatted like 'hh:mm:ss' to seconds using TTimeSpan.Parse.
Returns -1 if the string does not contain a valid time.
Note: TTimeSpan.Parse expects 'hh:mm:ss' format (or '[d.]hh:mm:ss[.fffffff]').
It does NOT support 'mm:ss' shorthand.
Examples:
StringToSeconds('00:01:30') // returns 90 (1 min 30 sec)
StringToSeconds('01:30:00') // returns 5400 (1 hour 30 min)
StringToSeconds('1.30') // returns -1 (invalid format)
StringToSeconds('x') // returns -1 (invalid) }
function StringToSeconds(CONST s: String): Integer;
VAR TimeSpan: TTimeSpan;
begin
TRY
TimeSpan:= System.TimeSpan.TTimeSpan.Parse(s);
Result:= Round(TimeSpan.TotalSeconds);
EXCEPT
Result:= -1;
END;
end;
{ Returns True if the string can be parsed as a valid date (locale-dependent). }
function StringIsDate(CONST s: string): Boolean;
begin
Result:= True;
TRY
StrToDate(s);
EXCEPT
on EConvertError do
Result:= False;
END;
end;
{ Returns True if the string can be parsed as a valid time (locale-dependent). }
function StringIsTime(CONST s: string): Boolean;
begin
Result:= True;
TRY
StrToTime(s);
EXCEPT
on EConvertError do
Result:= False;
END;
end;
function CurrentYear: Word;
VAR aMonth, aDay : Word;
begin
DecodeDate(Now, Result, aMonth, aDay);
end;
function CurrentMonth: Word;
VAR aYear, aDay : Word;
begin
DecodeDate(Now, aYear, Result, aDay);
end;
function CurrentDay: Word;
VAR aMonth, aYear : Word;
begin
DecodeDate(Now, aYear, aMonth, Result);
end;
function CurrentHour: Word;
VAR aMin, aSec, mSec: Word;
begin
DecodeTime(Now, Result, aMin, aSec, mSec);
end;
{ Returns today as date (string) based on Locale. Example: Montag }
function TodayIs: string; // This is cross-platform
var
FormatSettings: TFormatSettings;
begin
FormatSettings := TFormatSettings.Create; // Use the current locale settings
Result := FormatDateTime('dddd', Now, FormatSettings);
end;
{ Returns today as date AND time. Example: 31.12.2021 - 16:50
Format: DD.MM.YYYY - HH:MM }
function CurrentDateToString: string;
VAR
Present: TDateTime;
Year, Month, Day: Word;
begin
Present:= Now;
DecodeDate(Present, Year, Month, Day);
Result:= IntToStr(Day)+'.'+IntToStr(Month)+'.'+IntToStr(Year)+' - '+ TimeToString(Present, FALSE);
end;
{ Returns time in short format (no seconds). Example: 16:50 }
function CurrentTimeToString(ShowSeconds: Boolean): string;
begin
Result:= TimeToString(Now, ShowSeconds);
end;
{ Returns time in short format. Example: 16:50 }
function TimeToString(CONST T: TDateTime; ShowSeconds: Boolean): string;
VAR
Hour, Min, Sec, MSec: Word;
begin
DecodeTime(T, Hour, Min, Sec, MSec);
if Hour < 10
then Result:= '0'+ IntToStr(Hour)
else Result:= IntToStr(Hour);
if Min < 10
then Result:= Result+ ':'+ '0'+IntToStr(Min)
else Result:= Result+ ':'+ IntToStr(Min);
if ShowSeconds then
if Sec < 10
then Result:= Result+ ':'+ '0'+IntToStr(Sec)
else Result:= Result+ ':'+ IntToStr(Sec);
end;
function DateIsToday(Year, Month, Day: word): Boolean; { Returns true if the specified date is today }
VAR NewDate: TDateTime;
begin
NewDate:= EncodeDate(Year, Month, Day);
Result:= IsToday(NewDate);
end;
{ Converts a TDate to Cardinal by counting days since Delphi epoch (30 Dec 1899).
Note: TDateTime value 0 corresponds to 30 Dec 1899, not 01 Jan 1899. }
function Date2Cardinal(xDate: TDate): Cardinal;
begin
Result:= DaysBetween(xDate, 0);
end;
{ Converts a Cardinal back to TDate by adding days to Delphi epoch (30 Dec 1899).
This is the inverse of Date2Cardinal. }
function Cardinal2Date(xCardinal: Cardinal): TDate;
begin
Result:= IncDay(0, xCardinal);
end;
{ Converts TDateTime to total milliseconds since Delphi epoch.
Copied from DateUtils.PAS where it is marked as 'Internal'.
Note: The internal DateUtils version has precision issues for very large/small dates.
See: stackoverflow.com/questions/17109814/why-datetimetomilliseconds-in-dateutils-pas-is-marked-as-internal }
function DateTimeToMilliseconds(aDateTime: TDateTime): Int64;
var
LTimeStamp: TTimeStamp;
begin
LTimeStamp := DateTimeToTimeStamp(ADateTime);
Result := LTimeStamp.Date;
Result := (Result * MSecsPerDay) + LTimeStamp.Time;
end;
{ Returns the number of seconds remaining until MilestoneDate.
Unlike DateUtils.SecondsBetween (which returns absolute difference), this function:
- Returns positive value when MilestoneDate is in the future
- Returns 0 when CurrentDate >= MilestoneDate (milestone already passed)
Useful for countdown timers. }
function SecondsBetweenEx(CONST MilestoneDate, CurrentDate: TDateTime): Int64;
begin
if CurrentDate < MilestoneDate
then Result := (DateTimeToMilliseconds(MilestoneDate) - DateTimeToMilliseconds(CurrentDate)) DIV (MSecsPerSec)
else Result := 0;
end;
{ Comparing '31 Dec 1999 23:59' and '1 Jan 2000 00:01' (2 minutes difference):
DaySpan returns 0.03 (fractional days)
DaysBetween returns 0 (whole days only)
NewDaysBetween returns 1.03 (counts partial days as a full day boundary crossed) }
function DaysBetweenEx(CONST MilestoneDate, CurrentDate: TdateTime): Double;
begin
RAISE exception.Create('DaysBetweenEx is deprecated. Use System.DateUtils.DaySpan instead.');
end;
{ Returns the number of days between two dates, counting each calendar day boundary crossed.
Unlike DaySpan (which returns only fractional days), this adds 1 when dates differ
to account for the calendar day boundary crossing.
Example: '31 Dec 23:59' to '1 Jan 00:01' = ~0.03 DaySpan + 1 = 1.03 }
function NewDaysBetween(CONST MilestoneDate, CurrentDate: TdateTime): Double;
begin
if SameDate(MilestoneDate, CurrentDate)
then Result := DaySpan(MilestoneDate, CurrentDate)
else Result := DaySpan(MilestoneDate, CurrentDate) + 1;
end;
{ Exaclty the same as DaysBetweenEx but uses a different approach to calculate it
function DaySpanEx(CONST MilestoneDate, CurrentDate: TDateTime): Double;
begin
Result := Abs(DateTimeToMilliseconds(MilestoneDate) - DateTimeToMilliseconds(CurrentDate)) / MSecsPerDay;
end; }
end.