-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeprint.cpp
1515 lines (1198 loc) · 55.1 KB
/
timeprint.cpp
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
This program prints the current date and time to the standard output stream.
It takes an optional format string to control the output.
*******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <sys/stat.h>
#include <cstdarg>
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <vector>
using std::time_t;
using std::tm;
using std::vector;
using std::wcout;
using std::wstring;
static auto version = L"timeprint 3.0.0-alpha.21 | 2023-11-21 | https://github.com/hollasch/timeprint";
enum class HelpType {
// Types of usage information for the --help option
None,
Full,
Version,
General,
Examples,
DeltaTime,
FormatCodes,
TimeSyntax,
TimeZone,
};
enum class OptionType {
// Command-Line Option Types
None,
AccessTime,
CodeChar,
CreationTime,
Help,
ModificationTime,
Now,
Time,
TimeZone,
Version,
};
enum class TimeType {
// Type of time for an associated time value string
None, // Not a legal time
Now, // Current time
Explicit, // Explicit ISO-8601 date/time
Access, // Access time of the named file
Creation, // Creation time of the named file
Modification // Modification time of the named file
};
class TimeSpec {
public:
TimeType type { TimeType::None }; // Type of time
wstring value; // String value of specified type
void Set(TimeType t, const wstring& str) {
type = t;
value = str;
}
void Set(TimeType t) {
type = t;
value.clear();
}
};
class Parameters {
// Describes the parameters for a run of this program.
public:
wchar_t codeChar { L'%' }; // Format Code Character (default '%')
HelpType helpType { HelpType::None }; // Type of help information to print & exit
wstring zone; // Time zone string
wstring format; // Output format string
bool isDelta { false }; // Time calculation is a difference between two times
TimeSpec time1; // Time 1 [required] (either single use, or for time difference)
TimeSpec time2; // Time 2 [optional] (for time difference output)
};
// Global Constants
static const int secondsPerMinute = 60;
static const int secondsPerHour = secondsPerMinute * 60;
static const int secondsPerDay = secondsPerHour * 24;
static const int secondsPerNominalYear = secondsPerDay * 365;
static const int secondsPerTropicalYear = secondsPerNominalYear + (secondsPerDay / 400) * 497; // 365+97/400 days
// Global Variables
static time_t currentTime;
static tm currentTimeLocal;
static tm currentTimeUTC;
static int timeZoneOffsetHours; // Signed hours offset from UTC
static int timeZoneOffsetMinutes; // Signed minutes offset from UTC
//======================================================================================================================
// Help Text
//======================================================================================================================
static auto help_general = LR"(
timeprint: Print time and date information
usage : timeprint [--codeChar <char>] [-%<char>]
[--help [topic]] [-h[topic]] [/?] [--version]
[--<access|accessed> <file>] [-a<file>]
[--<create|created|creation> <file>] [-c<file>]
[--<modify|modified|modification> <file>] [-m<file>]
[--timeZone <zone>] [-z<zone>]
[--now] [-n]
[--time <timeValue>] [-t<timeValue>]
[string] ... [string]
This command prints time information to the standard output stream. All string
fragments will be concatenated with a space, so it's often unnecessary to quote
the format string.
timeprint operates in either absolute or differential mode. If one time value
is specified, then values for that absolute time are reported. If two time
values are supplied, then timeprint reports the values for the positive
difference between those two values. If no time values are given, then --now
is implied.
Single-letter command options that take an argument may be specified with or
without token separation. (For example, both `-htimeSyntax` and `-h timeSyntax`
are valid.)
--help [topic], -h[topic], /?
Print help and usage information in general, or for the optional
specified topic. Topics include 'full', 'examples', 'version',
'delta'/'deltaTime'/'deltaTimes', 'format'/'formatCode'/'formatCodes',
'timeSyntax', and 'timeZone'/'timeZones'.
--version
Print version information.
--codeChar <char>, -%<char>
The --codeChar switch specifies an alternate code character to the
default '%' character. If the backslash (\) is specified as the code
character, then normal backslash escapes will be disabled. The
--codeChar switch is ignored unless the format string is specified on
the command line.
--timeZone <zone>, -z<zone>
The --timeZone argument takes a timezone string of the form used by the
TZ environment variable and displays the result in that time zone. If no
timezone is specified, the value in the TZ environment variable is used.
If the environment variable TZ is unset, the system local time is used.
For a description of the time zone format, use `--help timeZone`.
--now, -n
Use the current time. This is useful when specifying one of two time
values for delta time printing. For absolute time printing, `--now` is
the default.
--time <value>, -t<value>
Specifies an explicit absolute time, using ISO 8601 syntax. For a
description of supported syntax, use `--help timeSyntax`.
--access|--accessed <fileName>, -a<fileName>
Use the time of last access of the named file for a time value.
--create|--created|--creation <fileName>, -c<fileName>
Use the creation time of the named file.
--modify|--modified|--modification <fileName>, -m<fileName>
Use the modification time of the named file.
If no output string is supplied, the format specified in the environment
variable TIMEFORMAT is used. If this variable is not set, then the format
defaults to "%#c". The TIMEFORMAT string must use the "%" code character.
Similarly, the default difference time format may be specified with the
TIMEFORMAT_DELTA environment variable. If this variable is not set, then the
format defaults to "%_Y years, %_yD days, %_d0H:%_h0M:%_m0S". The
TIMEFORMAT_DELTA string must use the "%" code character.
Note that if your format string begins with - or /, you will need to prefix it
with a \ character so that it is not confused with a command switch.
Strings take both \-escaped characters and %-codes in the style of printf.
The escape codes include \n (newline), \t (tab), \b (backspace),
\r (carriage return), and \a (alert, or beep).
For a full description of supported time format codes, use
`--help format`.
For additional help, use `--help <topic>`, where <topic> is one of:
- timeSyntax
- timeZone / timeZones
- format / formatCode / formatCodes
- delta / deltaTime / deltaTimes
- examples
- full
)";
//__________________________________________________________________________________________________
static auto help_examples = LR"(
Examples
---------
> timeprint
Sunday, July 20, 2003 17:02:39
> timeprint %H:%M:%S
17:03:17
> timeprint -z UTC
Monday, July 21, 2003 00:03:47
> timeprint Starting build at %Y-%m-%d %#I:%M:%S %p.
Starting build at 2003-07-20 5:06:09 PM.
> echo. >timestamp.txt
[a day and a half later...]
> timeprint --modification timestamp.txt --now Elapsed Time: %_S seconds
Elapsed Time: 129797 seconds
> timeprint --modification timestamp.txt --now Elapsed Time: %_H:%_hM:%_mS
Elapsed Time: 36:3:17
)";
//__________________________________________________________________________________________________
static auto help_deltaTime = LR"(
Delta Time Formatting
----------------------
Time differences are reported using the delta time formats. The delta time
format has the following syntax:
%_['kd][u[0]]<U>[.[#]]
-v- -v-- v --v-
Numeric Format --------' | | |
Next Greater Unit ----------' | |
Units ---------------------------' |
Decimal Precision --------------------'
Numeric Format ['kd] (_optional_)
The optional `'` character is followed by two characters, k and d.
k represents the character to use for the thousand's separator, with
the special case that `0` indicates that there is to be no thousands
separator. The d character is the character to use for the decimal
point, if one is present. So, for example, `'0.` specifies no
thousands separator, and the American `.` decimal point. `'.,` would
specify European formatting, with `.` for the thousands separator, and
`,` as the decimal point.
Next Greater Unit [u[0]] (_optional_)
This single lowercase letter indicates any preceding units used in the
delta time printing. For example, if the unit is hours, and the next
greater unit is years, then the hours reported are the remainder
(modulo) after the number of years. Supported next greater units
include the following:
y - Nominal years (see units below for definition)
t - Tropical years (see units below for definition)
d - Days
h - Hours
m - Minutes
If the next greater unit is followed by a zero, then the result is
zero-padded to the appropriate width for the range of possible values.
Units <U> (_required_)
The unit of time (single uppercase letter) to report for the time
delta. This is the remainder after the (optional) next greater unit.
The following units are supported:
Y - Nominal years
T - Tropical years
D - Days
H - Hours
M - Minutes
S - Whole seconds
Nominal years are 365 days in length.
Tropical (or solar) years are approximately equal to one trip around
the sun. These are useful to approximate the effect of leap years when
reporting multi-year durations. For this program, a tropical year is
defined as 365 + 97/400 days.
The following are the supported combinations of next greater unit and
unit:
Y
T
D yD tD
H yH tH dH
M yM tM dM hM
S yS tS dS hS mS
Decimal Precision [.[#]] (_optional_)
With the exception of seconds, all units will have a fractional value
for time differences. If the decimal precision format is omitted, the
then rounded whole value is printed.
If the decimal point and number is specified, then the fractional
value will be printed with the number of requested digits.
If a decimal point is specified but without subsequent digits, then
the number of digits will depend on the units. Enough digits will be
printed to maintain full resolution of the unit to within one second.
Thus, years: 8 digits, days: 5, hours: 4, minutes: 2.
Examples
Given a delta time of 547,991,463 seconds, the following delta format
strings will yield the following output:
%_S
'547991463'
%_',.S
'547,991,463'
%_Y years, %_yD days, %_dH. hours
'17 years, 137 days, 11.8508 hours'
See `--time examples` for more example uses of delta time formats.
)";
//__________________________________________________________________________________________________
static auto help_formatCodes = LR"(
Format Codes
-------------
The following time format codes are supported:
Date, Full
%D Short MM/DD/YY date, equivalent to %m/%d/%y
%F Short YYYY-MM-DD date, equivalent to %Y-%m-%d
%x * Date representation
Date Components
%b * Abbreviated month name
%B * Full month name
%C Year divided by 100 and truncated to integer (00-99)
%d Day of month as decimal number (01-31)
%e Day of the month, space-padded ( 1-31)
%G Week-based year
%g Week-based year, last two digits (00-99)
%H Hour in 24-hour format (00-23)
%i Full date and time in ISO-8601 format
%I Hour in 12-hour format (01-12)
%h * Abbreviated month name (same as %b)
%j Day of year as decimal number (001-366)
%m Month as decimal number (01-12)
%Y Year with century, as decimal number
%y Year without century, as decimal number (00-99)
Week
%U Week number, first Sunday = week 1 day 1 (00-53)
%V ISO 8601 week number (01-53)
%W Week of year, decimal, Monday = week 1 day 1 (00-51)
Week Day
%<d>a Weekday name, abbreviated to d characters (min 1)
%a * Abbreviated weekday name
%A * Full weekday name
%u ISO 8601 weekday as number with Monday=1 (1-7)
%w Weekday as decimal number, Sunday=0 (0-6)
Time, Full
%r * 12-hour clock time
%R 24-hour HH:MM time, equivalent to %H:%M
%T ISO 8601 time format (HH:MM:SS) equivalent to %H:%M:%S
%X * Time representation
Time Components
%H Hour in 24-hour format (00-23)
%I Hour in 12-hour format (01-12)
%M Minute as decimal number (00-59)
%p AM or PM designation (locale dependent)
%S Seconds as a decimal number (00-59)
%z ISO 8601 offset from UTC in timezone (1 minute=1, 1 hour=100)
If timezone cannot be determined, no characters
%Z * Time-zone name or abbreviation.
If timezone cannot be determined, no characters
Date + Time
%c * Date and time representation
%i Full date and time in ISO-8601 format
Time/Date Difference
%_... Delta time formats. See `--help deltaTime`.
Special Characters
%% Percent sign
%n New line character (same as '\n')
%t Horizontal tab character (same as '\t')
* Specifiers marked with an asterisk are locale-dependent.
As in the printf function, the # flag may prefix any formatting code. In
that case, the meaning of the format code is changed as follows.
%#c
Long date and time representation, appropriate for current locale.
For example: Tuesday, March 14, 1995, 12:41:29.
%#x
Long date representation, appropriate to current locale.
For example: Tuesday, March 14, 1995.
%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y
Remove any leading zeros.
All others
The flag is ignored.
)";
//__________________________________________________________________________________________________
static auto help_timeSyntax = LR"(
Time Syntax
------------
The explicit `--time` option supports a variety of different formats,
based on the ISO 8601 date/time format.
An explicit date-time may have a date, a time, or both. In the case of
both, they must be separated by the letter `T`. No spaces are allowed in
the string.
The date can take one of the following patterns, where a `=` character
denotes a required dash, and a `-` denotes an optional dash:
YYYY-MM-DD
YYYY=MM
YYYY
==MM-DD
YYYY-DDD (DDD = day of the year)
The time can take one of the following patterns, where the `:` characters
are optional:
HH:MM:SS
HH:MM
HH
The time may be followed by an optional time zone, which has the following
pattern, where `+` represents a required `+` or `-` character.
+HHMM (Offset from UTC)
+HH (Offset from UTC)
Z (Zulu, or UTC)
Parsing the explicit time value takes place as follows: if the string
contains a `T`, then the date is parsed before the `T`, and the time is
parsed after. If the string contains no `T`, then time parsing is first
attempted, and on failure date parsing is attempted. Again, parsing is
strict, and no other characters may included anywhere.
Any unspecified units get the current time value for that unit.
Example explicit time values include the following:
2018-02-24T20:58:46-0800
2018-02-25T04:58:46Z
17:57
--05-07
120000Z
1997-183
19731217T113618-0700
See `--help examples` for other examples.
)";
//__________________________________________________________________________________________________
static auto help_timeZone = LR"(
Time Zones
-----------
The time zone value may be specified with the TZ environment variable,
or using the `--timezone` option. Time zones have the format
`tzn[+|-]hh[:mm[:ss]][dzn]`, where
tzn
Time-zone name, three letters or more, such as PST.
[+|-]hh
The time that must be ADDED to local time to get UTC.
CAREFUL: Unfortunately, this value is negated from how time zones
are normally specified. For example, PDT is specified as -0800,
but in the time zone string, will be specified as `PDT+08`.
You can experiment with the string "%#c %Z %z" and the
`--timezone` option to ensure you understand how these work
together. If offset hours are omitted, they are assumed to be
zero.
[:mm]
Minutes, prefixed with mandatory colon.
[:ss]
Seconds, prefixed with mandatory colon.
[dzn]
Three-letter daylight-saving-time zone such as PDT. If daylight
saving time is never in effect in the locality, omit dzn. The C
run-time library assumes the US rules for implementing the
calculation of Daylight Saving Time (DST).
Examples of the timezone string include the following:
UTC Universal Coordinated Time
PST8 Pacific Standard Time
PDT+07 Pacific Daylight Time
NST+03:30 Newfoundland Standard Time
PST8PDT Pacific Standard Time, daylight savings in effect
GST-1GDT German Standard Time, daylight savings in effect
)";
//__________________________________________________________________________________________________
void help (HelpType type) {
// For HelpType::None, do nothing. For other help types, print corresponding help information
// and exit.
switch (type) {
default: return;
case HelpType::General:
_putws(help_general);
_putws(version);
break;
case HelpType::Version: _putws(version); break;
case HelpType::Examples: _putws(help_examples); break;
case HelpType::DeltaTime: _putws(help_deltaTime); break;
case HelpType::FormatCodes: _putws(help_formatCodes); break;
case HelpType::TimeSyntax: _putws(help_timeSyntax); break;
case HelpType::TimeZone: _putws(help_timeZone); break;
case HelpType::Full:
_putws(help_general);
_putws(help_timeSyntax);
_putws(help_timeZone);
_putws(help_formatCodes);
_putws(help_deltaTime);
_putws(help_examples);
_putws(L"");
_putws(version);
break;
}
exit (0);
}
//======================================================================================================================
// Utility Functions
//======================================================================================================================
bool errorMsg (const wchar_t *message, ...) {
// Prints printf-style error message to stderr output stream. This function always returns false
// (for chaining).
va_list(arguments);
va_start(arguments, message);
wstring fullMessage = L"timeprint: ";
fullMessage += message;
fullMessage += L".\n";
vfwprintf_s (stderr, fullMessage.c_str(), arguments);
va_end(arguments);
return false;
}
//__________________________________________________________________________________________________
bool equalIgnoreCase (const wchar_t* str1, const wchar_t* str2) {
return 0 == _wcsicmp(str1, str2);
}
//__________________________________________________________________________________________________
bool charIn (wchar_t c, const wchar_t* list) {
// Return true if the given character is in the zero-terminated array of characters.
// Also returns true if c == 0.
auto i = 0;
while (list[i] && (c != list[i]))
++i;
return (c == list[i]);
}
//__________________________________________________________________________________________________
int getNumIntDigits (double x) {
// Returns the number of digits in the given integer value.
int n = static_cast<int>(x);
int nDigits = 1;
while (n /= 10)
++ nDigits;
return nDigits;
}
//__________________________________________________________________________________________________
void getCurrentTime () {
// This function gets the current local time, and the corresponding local and UTC time structs.
// It also gets the current time zone's hour & minute offsets from UTC.
currentTime = std::time(nullptr);
localtime_s (¤tTimeLocal, ¤tTime);
gmtime_s (¤tTimeUTC, ¤tTime);
// Figure out the local time zone's offset. Computing the difference between local and UTC times
// is problematic, particularly when the local time zone is changing in or out of daylight
// saving time. Given this, the best approach is to get the actual time zone offset from the
// system ftime() function family. This returns a string of the form "[+|-]HHMM".
wchar_t buffer[8];
wcsftime (buffer, std::size(buffer), L"%z", ¤tTimeLocal);
timeZoneOffsetHours = 10*(buffer[1]-L'0') + (buffer[2]-L'0'); // Parse out unsigned offset hours
timeZoneOffsetMinutes = 10*(buffer[3]-L'0') + (buffer[4]-L'0'); // Parse out unsigned offset minutes
// Handle possible negative sign.
if (buffer[0] == L'-') {
timeZoneOffsetHours = -timeZoneOffsetHours;
timeZoneOffsetMinutes = -timeZoneOffsetMinutes;
}
}
//__________________________________________________________________________________________________
wstring defaultTimeFormat (bool deltaFormat) {
// Returns the default time format for the absolute or delta time, either from the user's
// environment variable, or from a standard default time format.
wchar_t* timeFormatEnv;
wstring defaultFormat;
if (deltaFormat) {
_wdupenv_s (&timeFormatEnv, nullptr, L"TimeFormat_Delta");
defaultFormat = timeFormatEnv ? timeFormatEnv : L"%_Y years, %_yD days, %_d0H:%_h0M:%_m0S";
} else {
_wdupenv_s (&timeFormatEnv, nullptr, L"TimeFormat");
defaultFormat = timeFormatEnv ? timeFormatEnv : L"%#c";
}
free (timeFormatEnv);
return defaultFormat;
}
//======================================================================================================================
// Date/Time Parsing Functions
//======================================================================================================================
bool parseDateTimePatternCore (
wchar_t* pattern,
wstring::iterator& sourceIt,
wstring::iterator sourceEnd,
vector<int>& results)
{
// This is the core functionality of the explicit date & time parsing. Returns true if the given
// pattern matches the source, and places the parsed integer results in the results vector.
// Patterns may include the following characters:
//
// #... A sequence of digits yielding one number
// + A sign character, either '+' or '-'. Yields +1 or -1, respectively.
// - An optional dash.
// = A mandatory dash.
// : An optional colon.
// ... Anything else must match exactly.
results.clear();
auto sourceStart = sourceIt;
auto numberValue = 0;
auto capturingNumber = false;
for (auto patternChar=pattern; *patternChar; ++patternChar, ++sourceIt) {
if (sourceIt == sourceEnd) return false;
if (capturingNumber && (*patternChar != '#')) {
results.push_back (numberValue);
numberValue = 0;
capturingNumber = false;
}
switch (*patternChar) {
// Captured elements
case L'#': {
if (!isdigit(*sourceIt)) return false;
numberValue = (10 * numberValue) + (*sourceIt - '0');
capturingNumber = true;
break;
}
case L'+': {
if (*sourceIt == L'-')
results.push_back (-1);
else if (*sourceIt == L'+')
results.push_back (1);
else
return false;
break;
}
// Non-captured elements
case L'-': {
if (*sourceIt != L'-') --sourceIt;
break;
}
case L'=': {
if (*sourceIt != L'-') return false;
break;
}
case L':': {
if (*sourceIt != L':') --sourceIt;
break;
}
default: {
if (*sourceIt != *patternChar) return false;
break;
}
}
}
if (capturingNumber)
results.push_back (numberValue);
return true;
}
//__________________________________________________________________________________________________
bool parseDateTimePattern (
wchar_t* pattern,
wstring::iterator& sourceIt,
wstring::iterator sourceEnd,
vector<int>& results)
{
// Parses a date/time pattern. On failure, restores the sourceIt iterator and returns false,
// otherwise on success leaves the sourceIt where it ended and returns true.
wstring::iterator sourceReset = sourceIt;
if (!parseDateTimePatternCore (pattern, sourceIt, sourceEnd, results)) {
sourceIt = sourceReset;
return false;
}
return true;
}
//__________________________________________________________________________________________________
bool getExplicitTime (tm& resultTimeLocal, wstring::iterator specBegin, wstring::iterator specEnd) {
// Parses the time part of an ISO 8601 date string. Returns true on success, false on failure.
bool gotTime = false;
vector<int> results;
wstring::iterator specIt = specBegin;
if (parseDateTimePattern (L"##:##:##", specIt, specEnd, results)) {
resultTimeLocal.tm_hour = results[0];
resultTimeLocal.tm_min = results[1];
resultTimeLocal.tm_sec = results[2];
gotTime = true;
} else if (parseDateTimePattern (L"##:##", specIt, specEnd, results)) {
resultTimeLocal.tm_hour = results[0];
resultTimeLocal.tm_min = results[1];
gotTime = true;
} else if (parseDateTimePattern (L"##", specIt, specEnd, results)) {
resultTimeLocal.tm_hour = results[0];
gotTime = true;
}
if (!gotTime) return false;
// Parse timezone, if any.
if (specIt == specEnd) {
// Time was specified in local time, no conversion needed.
return true;
}
if ((specIt[0] == L'Z') && (std::next(specIt) == specEnd)) {
// UTC time; convert to local. We just do this manually by applying the offset.
resultTimeLocal.tm_hour += timeZoneOffsetHours;
resultTimeLocal.tm_min += timeZoneOffsetMinutes;
return true;
}
// Attempt to parse the explicit timezone from the spec.
auto specOffsetHours = 0;
auto specOffsetMinutes = 0;
if (parseDateTimePattern (L"+##:##", specIt, specEnd, results)) {
specOffsetHours = results[0] * results[1];
specOffsetMinutes = results[0] * results[2];
} else if (parseDateTimePattern (L"+##", specIt, specEnd, results)) {
specOffsetHours = results[0] * results[1];
}
if (specIt != specEnd) return false;
// Convert from specified time zone to UTC, then to local time.
resultTimeLocal.tm_hour += -specOffsetHours + timeZoneOffsetHours;
resultTimeLocal.tm_min += -specOffsetMinutes + timeZoneOffsetMinutes;
return true;
}
//__________________________________________________________________________________________________
bool getExplicitDate (tm& resultTime, wstring::iterator specBegin, wstring::iterator specEnd) {
// Parses the date part of an ISO 8601 date string. Returns true on success, false on failure.
auto gotDate = false;
vector<int> results;
wstring::iterator specIt = specBegin;
if (parseDateTimePattern (L"==##-##", specIt, specEnd, results)) {
resultTime.tm_mon = results[0] - 1;
resultTime.tm_mday = results[1];
gotDate = true;
} else if (parseDateTimePattern (L"####-##-##", specIt, specEnd, results)) {
resultTime.tm_year = results[0] - 1900;
resultTime.tm_mon = results[1] - 1;
resultTime.tm_mday = results[2];
gotDate = true;
} else if (parseDateTimePattern (L"####-###", specIt, specEnd, results)) {
resultTime.tm_year = results[0] - 1900;
resultTime.tm_mon = 0;
resultTime.tm_mday = results[1];
gotDate = true;
} else if (parseDateTimePattern (L"####=##", specIt, specEnd, results)) {
resultTime.tm_year = results[0] - 1900;
resultTime.tm_mon = results[1] - 1;
gotDate = true;
} else if (parseDateTimePattern (L"####", specIt, specEnd, results)) {
resultTime.tm_year = results[0] - 1900;
gotDate = true;
}
return gotDate && (specIt == specEnd);
}
//__________________________________________________________________________________________________
bool getExplicitDateTime (time_t& result, wstring timeSpec) {
// Parses an ISO 8601 formatted date/time string. Returns true on success, false on failure.
tm timeStruct = currentTimeLocal;
auto dateTimeSep = std::find (timeSpec.begin(), timeSpec.end(), 'T');
bool successResult;
if (dateTimeSep != timeSpec.end()) {
successResult = getExplicitTime (timeStruct, std::next(dateTimeSep), timeSpec.end())
&& getExplicitDate (timeStruct, timeSpec.begin(), dateTimeSep);
} else {
successResult = getExplicitTime (timeStruct, timeSpec.begin(), timeSpec.end())
|| getExplicitDate (timeStruct, timeSpec.begin(), timeSpec.end());
}
if (successResult) {
if (timeStruct.tm_year < 70)
return errorMsg(L"Cannot handle dates before 1970");
timeStruct.tm_isdst = -1; // DST status unknown
result = mktime (&timeStruct);
}
return successResult;
}
//__________________________________________________________________________________________________
bool getTimeFromSpec (time_t& result, const TimeSpec& spec) {
// Gets the time specified by the given time specification.
if (spec.type == TimeType::Now) {
result = currentTime;
return true;
}
if ( (spec.type == TimeType::Access)
|| (spec.type == TimeType::Creation)
|| (spec.type == TimeType::Modification)) {
struct _stat stat; // File Status Data
auto fileName = spec.value.c_str();
if (0 != _wstat(fileName, &stat))
return errorMsg(L"Couldn't get status of \"%s\"", fileName);
switch (spec.type) {
case TimeType::Access: result = stat.st_atime; break;
case TimeType::Creation: result = stat.st_ctime; break;
case TimeType::Modification: result = stat.st_mtime; break;
}
return true;
}
if (spec.type == TimeType::Explicit) {
auto timeString = spec.value;
if (getExplicitDateTime(result, timeString))
return true;
return errorMsg(L"Unrecognized explicit time: \"%s\"", timeString.c_str());
}
return false; // Unrecognized time type
}
//__________________________________________________________________________________________________
bool calcTime (
const Parameters& params, // Command parameters
tm& timeValue, // Output time value
time_t& deltaTimeSeconds) // Output time delta in seconds
{
// This function computes the time results and then sets the timeValue and deltaTimeSeconds
// parameters. This function returns true on success, false on failure.
// If an alternate time zone was specified, then we need to set the TZ environment variable.
if (!params.zone.empty()) {
_wputenv_s (L"TZ", params.zone.c_str());
}
getCurrentTime(); // Snapshot current time data to global variables.
time_t time1;
if (!getTimeFromSpec (time1, params.time1)) return false;
if (params.time2.type == TimeType::None) { // Reporting a single absolute time.
deltaTimeSeconds = 0;
localtime_s (&timeValue, &time1);
} else { // Reporting a time diffence
time_t time2;
if (!getTimeFromSpec (time2, params.time2)) return false;
deltaTimeSeconds = (time1 < time2) ? (time2 - time1) : (time1 - time2);
gmtime_s (&timeValue, &deltaTimeSeconds);
}
return true;
}
//======================================================================================================================
// Delta Time Processing
//======================================================================================================================
bool getDeltaNumberFormat (
wstring::iterator& formatIterator,
const wstring::iterator& formatEnd,
wchar_t& thousandsChar,
wchar_t& decimalChar)
{
// This function parses the thousands separator and decimal point formatting sequence, if it
// exists. On return, `thousandsChar` will contain the thousands character, or zero if no
// thousands character is to be printed, and `decimalChar` will contain the decimal character to
// use, or 0 to use a '.' decimal point.
thousandsChar = 0;
decimalChar = 0;
if (*formatIterator == L'\'') {
if (++formatIterator == formatEnd) return false;
thousandsChar = *formatIterator;
if (++formatIterator == formatEnd) return false;
decimalChar = *formatIterator;
if (++formatIterator == formatEnd) return false;
if (thousandsChar == L'0') // '0' indicates no thousands character.
thousandsChar = 0;
}
return true;
}
//__________________________________________________________________________________________________