-
-
Notifications
You must be signed in to change notification settings - Fork 702
/
systime.d
11831 lines (10154 loc) · 513 KB
/
systime.d
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
// Written in the D programming language
/++
$(SCRIPT inhibitQuickIndex = 1;)
$(DIVC quickindex,
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Types) $(TD
$(LREF Clock)
$(LREF SysTime)
$(LREF DosFileTime)
))
$(TR $(TD Conversion) $(TD
$(LREF parseRFC822DateTime)
$(LREF DosFileTimeToSysTime)
$(LREF FILETIMEToStdTime)
$(LREF FILETIMEToSysTime)
$(LREF stdTimeToFILETIME)
$(LREF stdTimeToUnixTime)
$(LREF SYSTEMTIMEToSysTime)
$(LREF SysTimeToDosFileTime)
$(LREF SysTimeToFILETIME)
$(LREF SysTimeToSYSTEMTIME)
$(LREF unixTimeToStdTime)
))
))
License: $(HTTP www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP jmdavisprog.com, Jonathan M Davis)
Source: $(PHOBOSSRC std/datetime/systime.d)
+/
module std.datetime.systime;
version (OSX)
version = Darwin;
else version (iOS)
version = Darwin;
else version (TVOS)
version = Darwin;
else version (WatchOS)
version = Darwin;
/// Get the current time as a $(LREF SysTime)
@safe unittest
{
import std.datetime.timezone : LocalTime;
SysTime today = Clock.currTime();
assert(today.timezone is LocalTime());
}
/// Construct a $(LREF SysTime) from a ISO time string
@safe unittest
{
import std.datetime.date : DateTime;
import std.datetime.timezone : UTC;
auto st = SysTime.fromISOExtString("2018-01-01T10:30:00Z");
assert(st == SysTime(DateTime(2018, 1, 1, 10, 30, 0), UTC()));
}
/// Make a specific point in time in the New York timezone
@safe unittest
{
import core.time : hours;
import std.datetime.date : DateTime;
import std.datetime.timezone : SimpleTimeZone;
auto ny = SysTime(
DateTime(2018, 1, 1, 10, 30, 0),
new immutable SimpleTimeZone(-5.hours, "America/New_York")
);
// ISO standard time strings
assert(ny.toISOString() == "20180101T103000-05:00");
assert(ny.toISOExtString() == "2018-01-01T10:30:00-05:00");
}
// Note: reconsider using specific imports below after
// https://issues.dlang.org/show_bug.cgi?id=17630 has been fixed
import core.time;// : ClockType, convert, dur, Duration, seconds, TimeException;
import std.datetime.date;// : _monthNames, AllowDayOverflow, CmpTimeUnits, Date,
//DateTime, DateTimeException, DayOfWeek, enforceValid, getDayOfWeek, maxDay,
//Month, splitUnitsFromHNSecs, TimeOfDay, validTimeUnits, yearIsLeapYear;
import std.datetime.timezone;// : LocalTime, SimpleTimeZone, TimeZone, UTC;
import std.exception : enforce;
import std.format : format;
import std.range.primitives;
import std.traits : isIntegral, isSigned, isSomeString, isNarrowString;
version (Windows)
{
import core.stdc.time : time_t;
import core.sys.windows.winbase;
import core.sys.windows.winnt;
import core.sys.windows.winsock2;
}
else version (Posix)
{
import core.sys.posix.signal : timespec;
import core.sys.posix.sys.types : time_t;
}
version (StdUnittest)
{
import core.exception : AssertError;
import std.exception : assertThrown;
}
@safe unittest
{
initializeTests();
}
version (unittest) private bool clockSupported(ClockType c)
{
// Skip unsupported clocks on older linux kernels, assume that only
// CLOCK_MONOTONIC and CLOCK_REALTIME exist, as that is the lowest
// common denominator supported by all versions of Linux pre-2.6.12.
version (Linux_Pre_2639)
return c == ClockType.normal || c == ClockType.precise;
else
return true;
}
/++
Effectively a namespace to make it clear that the methods it contains are
getting the time from the system clock. It cannot be instantiated.
+/
final class Clock
{
public:
/++
Returns the current time in the given time zone.
Params:
clockType = The $(REF ClockType, core,time) indicates which system
clock to use to get the current time. Very few programs
need to use anything other than the default.
tz = The time zone for the SysTime that's returned.
Throws:
$(REF DateTimeException,std,datetime,date) if it fails to get the
time.
+/
static SysTime currTime(ClockType clockType = ClockType.normal)(immutable TimeZone tz = LocalTime()) @safe
{
return SysTime(currStdTime!clockType, tz);
}
@safe unittest
{
import std.format : format;
import core.time;
assert(currTime().timezone is LocalTime());
assert(currTime(UTC()).timezone is UTC());
// core.stdc.time.time does not always use unix time on Windows systems.
// In particular, dmc does not use unix time. If we can guarantee that
// the MS runtime uses unix time, then we may be able run this test
// then, but for now, we're just not going to run this test on Windows.
version (Posix)
{
static import core.stdc.time;
static import std.math;
immutable unixTimeD = currTime().toUnixTime();
immutable unixTimeC = core.stdc.time.time(null);
assert(std.math.abs(unixTimeC - unixTimeD) <= 2);
}
auto norm1 = Clock.currTime;
auto norm2 = Clock.currTime(UTC());
assert(norm1 <= norm2, format("%s %s", norm1, norm2));
assert(abs(norm1 - norm2) <= seconds(2));
import std.meta : AliasSeq;
static foreach (ct; AliasSeq!(ClockType.coarse, ClockType.precise, ClockType.second))
{{
static if (clockSupported(ct))
{
auto value1 = Clock.currTime!ct;
auto value2 = Clock.currTime!ct(UTC());
assert(value1 <= value2, format("%s %s (ClockType: %s)", value1, value2, ct));
assert(abs(value1 - value2) <= seconds(2), format("ClockType.%s", ct));
}
}}
}
/++
Returns the number of hnsecs since midnight, January 1st, 1 A.D. for the
current time.
Params:
clockType = The $(REF ClockType, core,time) indicates which system
clock to use to get the current time. Very few programs
need to use anything other than the default.
Throws:
$(REF DateTimeException,std,datetime,date) if it fails to get the
time.
+/
static @property long currStdTime(ClockType clockType = ClockType.normal)() @trusted
{
static if (clockType != ClockType.coarse &&
clockType != ClockType.normal &&
clockType != ClockType.precise &&
clockType != ClockType.second)
{
static assert(0, format("ClockType.%s is not supported by Clock.currTime or Clock.currStdTime", clockType));
}
version (Windows)
{
FILETIME fileTime;
GetSystemTimeAsFileTime(&fileTime);
immutable result = FILETIMEToStdTime(&fileTime);
static if (clockType == ClockType.second)
{
// Ideally, this would use core.std.time.time, but the C runtime
// has to be using unix time for that to work, and that's not
// guaranteed on Windows. Digital Mars does not use unix time.
// MS may or may not. If it does, then this can be made to use
// core.stdc.time for MS, but for now, we'll leave it like this.
return convert!("seconds", "hnsecs")(convert!("hnsecs", "seconds")(result));
}
else
return result;
}
else version (Posix)
{
static import core.stdc.time;
enum hnsecsToUnixEpoch = unixTimeToStdTime(0);
version (Darwin)
{
static if (clockType == ClockType.second)
return unixTimeToStdTime(core.stdc.time.time(null));
else
{
import core.sys.posix.sys.time : gettimeofday, timeval;
timeval tv = void;
// Posix gettimeofday called with a valid timeval address
// and a null second parameter doesn't fail.
gettimeofday(&tv, null);
return convert!("seconds", "hnsecs")(tv.tv_sec) +
tv.tv_usec * 10 +
hnsecsToUnixEpoch;
}
}
else version (linux)
{
static if (clockType == ClockType.second)
return unixTimeToStdTime(core.stdc.time.time(null));
else
{
import core.sys.linux.time : CLOCK_REALTIME_COARSE;
import core.sys.posix.time : clock_gettime, CLOCK_REALTIME;
static if (clockType == ClockType.coarse) alias clockArg = CLOCK_REALTIME_COARSE;
else static if (clockType == ClockType.normal) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.precise) alias clockArg = CLOCK_REALTIME;
else static assert(0, "Previous static if is wrong.");
timespec ts = void;
immutable error = clock_gettime(clockArg, &ts);
// Posix clock_gettime called with a valid address and valid clock_id is only
// permitted to fail if the number of seconds does not fit in time_t. If tv_sec
// is long or larger overflow won't happen before 292 billion years A.D.
static if (ts.tv_sec.max < long.max)
{
if (error)
throw new TimeException("Call to clock_gettime() failed");
}
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
}
else version (FreeBSD)
{
import core.sys.freebsd.time : clock_gettime, CLOCK_REALTIME,
CLOCK_REALTIME_FAST, CLOCK_REALTIME_PRECISE, CLOCK_SECOND;
static if (clockType == ClockType.coarse) alias clockArg = CLOCK_REALTIME_FAST;
else static if (clockType == ClockType.normal) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.precise) alias clockArg = CLOCK_REALTIME_PRECISE;
else static if (clockType == ClockType.second) alias clockArg = CLOCK_SECOND;
else static assert(0, "Previous static if is wrong.");
timespec ts = void;
immutable error = clock_gettime(clockArg, &ts);
// Posix clock_gettime called with a valid address and valid clock_id is only
// permitted to fail if the number of seconds does not fit in time_t. If tv_sec
// is long or larger overflow won't happen before 292 billion years A.D.
static if (ts.tv_sec.max < long.max)
{
if (error)
throw new TimeException("Call to clock_gettime() failed");
}
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
else version (NetBSD)
{
static if (clockType == ClockType.second)
return unixTimeToStdTime(core.stdc.time.time(null));
else
{
import core.sys.netbsd.time : clock_gettime, CLOCK_REALTIME;
timespec ts = void;
immutable error = clock_gettime(CLOCK_REALTIME, &ts);
// Posix clock_gettime called with a valid address and valid clock_id is only
// permitted to fail if the number of seconds does not fit in time_t. If tv_sec
// is long or larger overflow won't happen before 292 billion years A.D.
static if (ts.tv_sec.max < long.max)
{
if (error)
throw new TimeException("Call to clock_gettime() failed");
}
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
}
else version (OpenBSD)
{
static if (clockType == ClockType.second)
return unixTimeToStdTime(core.stdc.time.time(null));
else
{
import core.sys.openbsd.time : clock_gettime, CLOCK_REALTIME;
static if (clockType == ClockType.coarse) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.normal) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.precise) alias clockArg = CLOCK_REALTIME;
else static assert(0, "Previous static if is wrong.");
timespec ts;
if (clock_gettime(clockArg, &ts) != 0)
throw new TimeException("Call to clock_gettime() failed");
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
}
else version (DragonFlyBSD)
{
import core.sys.dragonflybsd.time : clock_gettime, CLOCK_REALTIME,
CLOCK_REALTIME_FAST, CLOCK_REALTIME_PRECISE, CLOCK_SECOND;
static if (clockType == ClockType.coarse) alias clockArg = CLOCK_REALTIME_FAST;
else static if (clockType == ClockType.normal) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.precise) alias clockArg = CLOCK_REALTIME_PRECISE;
else static if (clockType == ClockType.second) alias clockArg = CLOCK_SECOND;
else static assert(0, "Previous static if is wrong.");
timespec ts = void;
immutable error = clock_gettime(clockArg, &ts);
// Posix clock_gettime called with a valid address and valid clock_id is only
// permitted to fail if the number of seconds does not fit in time_t. If tv_sec
// is long or larger overflow won't happen before 292 billion years A.D.
static if (ts.tv_sec.max < long.max)
{
if (error)
throw new TimeException("Call to clock_gettime() failed");
}
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
else version (Solaris)
{
static if (clockType == ClockType.second)
return unixTimeToStdTime(core.stdc.time.time(null));
else
{
import core.sys.solaris.time : clock_gettime, CLOCK_REALTIME;
static if (clockType == ClockType.coarse) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.normal) alias clockArg = CLOCK_REALTIME;
else static if (clockType == ClockType.precise) alias clockArg = CLOCK_REALTIME;
else static assert(0, "Previous static if is wrong.");
timespec ts = void;
immutable error = clock_gettime(clockArg, &ts);
// Posix clock_gettime called with a valid address and valid clock_id is only
// permitted to fail if the number of seconds does not fit in time_t. If tv_sec
// is long or larger overflow won't happen before 292 billion years A.D.
static if (ts.tv_sec.max < long.max)
{
if (error)
throw new TimeException("Call to clock_gettime() failed");
}
return convert!("seconds", "hnsecs")(ts.tv_sec) +
ts.tv_nsec / 100 +
hnsecsToUnixEpoch;
}
}
else static assert(0, "Unsupported OS");
}
else static assert(0, "Unsupported OS");
}
@safe unittest
{
import std.format : format;
import std.math : abs;
import std.meta : AliasSeq;
enum limit = convert!("seconds", "hnsecs")(2);
auto norm1 = Clock.currStdTime;
auto norm2 = Clock.currStdTime;
assert(norm1 <= norm2, format("%s %s", norm1, norm2));
assert(abs(norm1 - norm2) <= limit);
static foreach (ct; AliasSeq!(ClockType.coarse, ClockType.precise, ClockType.second))
{{
static if (clockSupported(ct))
{
auto value1 = Clock.currStdTime!ct;
auto value2 = Clock.currStdTime!ct;
assert(value1 <= value2, format("%s %s (ClockType: %s)", value1, value2, ct));
assert(abs(value1 - value2) <= limit);
}
}}
}
private:
@disable this();
}
/// Get the current time as a $(LREF SysTime)
@safe unittest
{
import std.datetime.timezone : LocalTime;
SysTime today = Clock.currTime();
assert(today.timezone is LocalTime());
}
/++
`SysTime` is the type used to get the current time from the
system or doing anything that involves time zones. Unlike
$(REF DateTime,std,datetime,date), the time zone is an integral part of
`SysTime` (though for local time applications, time zones can be ignored
and it will work, since it defaults to using the local time zone). It holds
its internal time in std time (hnsecs since midnight, January 1st, 1 A.D.
UTC), so it interfaces well with the system time. However, that means that,
unlike $(REF DateTime,std,datetime,date), it is not optimized for
calendar-based operations, and getting individual units from it such as
years or days is going to involve conversions and be less efficient.
For calendar-based operations that don't
care about time zones, then $(REF DateTime,std,datetime,date) would be
the type to use. For system time, use `SysTime`.
$(LREF Clock.currTime) will return the current time as a `SysTime`.
To convert a `SysTime` to a $(REF Date,std,datetime,date) or
$(REF DateTime,std,datetime,date), simply cast it. To convert a
$(REF Date,std,datetime,date) or $(REF DateTime,std,datetime,date) to a
`SysTime`, use `SysTime`'s constructor, and pass in the intended time
zone with it (or don't pass in a $(REF TimeZone,std,datetime,timezone), and
the local time zone will be used). Be aware, however, that converting from a
$(REF DateTime,std,datetime,date) to a `SysTime` will not necessarily
be 100% accurate due to DST (one hour of the year doesn't exist and another
occurs twice). To not risk any conversion errors, keep times as
`SysTime`s. Aside from DST though, there shouldn't be any conversion
problems.
For using time zones other than local time or UTC, use
$(REF PosixTimeZone,std,datetime,timezone) on Posix systems (or on Windows,
if providing the TZ Database files), and use
$(REF WindowsTimeZone,std,datetime,timezone) on Windows systems. The time in
`SysTime` is kept internally in hnsecs from midnight, January 1st, 1 A.D.
UTC. Conversion error cannot happen when changing the time zone of a
`SysTime`. $(REF LocalTime,std,datetime,timezone) is the
$(REF TimeZone,std,datetime,timezone) class which represents the local time,
and `UTC` is the $(REF TimeZone,std,datetime,timezone) class which
represents UTC. `SysTime` uses $(REF LocalTime,std,datetime,timezone) if
no $(REF TimeZone,std,datetime,timezone) is provided. For more details on
time zones, see the documentation for $(REF TimeZone,std,datetime,timezone),
$(REF PosixTimeZone,std,datetime,timezone), and
$(REF WindowsTimeZone,std,datetime,timezone).
`SysTime`'s range is from approximately 29,000 B.C. to approximately
29,000 A.D.
+/
struct SysTime
{
import core.stdc.time : tm;
version (Posix) import core.sys.posix.sys.time : timeval;
import std.typecons : Rebindable;
public:
/++
Params:
dateTime = The $(REF DateTime,std,datetime,date) to use to set
this $(LREF SysTime)'s internal std time. As
$(REF DateTime,std,datetime,date) has no concept of
time zone, tz is used as its time zone.
tz = The $(REF TimeZone,std,datetime,timezone) to use for this
$(LREF SysTime). If null,
$(REF LocalTime,std,datetime,timezone) will be used. The
given $(REF DateTime,std,datetime,date) is assumed to
be in the given time zone.
+/
this(DateTime dateTime, immutable TimeZone tz = null) @safe nothrow
{
try
this(dateTime, Duration.zero, tz);
catch (Exception e)
assert(0, "SysTime's constructor threw when it shouldn't have.");
}
@safe unittest
{
static void test(DateTime dt, immutable TimeZone tz, long expected)
{
auto sysTime = SysTime(dt, tz);
assert(sysTime._stdTime == expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz), format("Given DateTime: %s", dt));
}
test(DateTime.init, UTC(), 0);
test(DateTime(1, 1, 1, 12, 30, 33), UTC(), 450_330_000_000L);
test(DateTime(0, 12, 31, 12, 30, 33), UTC(), -413_670_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), UTC(), 0);
test(DateTime(1, 1, 1, 0, 0, 1), UTC(), 10_000_000L);
test(DateTime(0, 12, 31, 23, 59, 59), UTC(), -10_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), new immutable SimpleTimeZone(dur!"minutes"(-60)), 36_000_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), new immutable SimpleTimeZone(Duration.zero), 0);
test(DateTime(1, 1, 1, 0, 0, 0), new immutable SimpleTimeZone(dur!"minutes"(60)), -36_000_000_000L);
static void testScope(scope ref DateTime dt) @safe
{
auto st = SysTime(dt);
}
}
/++
Params:
dateTime = The $(REF DateTime,std,datetime,date) to use to set
this $(LREF SysTime)'s internal std time. As
$(REF DateTime,std,datetime,date) has no concept of
time zone, tz is used as its time zone.
fracSecs = The fractional seconds portion of the time.
tz = The $(REF TimeZone,std,datetime,timezone) to use for this
$(LREF SysTime). If null,
$(REF LocalTime,std,datetime,timezone) will be used. The
given $(REF DateTime,std,datetime,date) is assumed to
be in the given time zone.
Throws:
$(REF DateTimeException,std,datetime,date) if `fracSecs` is negative or if it's
greater than or equal to one second.
+/
this(DateTime dateTime, Duration fracSecs, immutable TimeZone tz = null) @safe
{
enforce(fracSecs >= Duration.zero, new DateTimeException("A SysTime cannot have negative fractional seconds."));
enforce(fracSecs < seconds(1), new DateTimeException("Fractional seconds must be less than one second."));
auto nonNullTZ = tz is null ? LocalTime() : tz;
immutable dateDiff = dateTime.date - Date.init;
immutable todDiff = dateTime.timeOfDay - TimeOfDay.init;
immutable adjustedTime = dateDiff + todDiff + fracSecs;
immutable standardTime = nonNullTZ.tzToUTC(adjustedTime.total!"hnsecs");
this(standardTime, nonNullTZ);
}
@safe unittest
{
import core.time;
static void test(DateTime dt, Duration fracSecs, immutable TimeZone tz, long expected)
{
auto sysTime = SysTime(dt, fracSecs, tz);
assert(sysTime._stdTime == expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz),
format("Given DateTime: %s, Given Duration: %s", dt, fracSecs));
}
test(DateTime.init, Duration.zero, UTC(), 0);
test(DateTime(1, 1, 1, 12, 30, 33), Duration.zero, UTC(), 450_330_000_000L);
test(DateTime(0, 12, 31, 12, 30, 33), Duration.zero, UTC(), -413_670_000_000L);
test(DateTime(1, 1, 1, 0, 0, 0), msecs(1), UTC(), 10_000L);
test(DateTime(0, 12, 31, 23, 59, 59), msecs(999), UTC(), -10_000L);
test(DateTime(0, 12, 31, 23, 59, 59), hnsecs(9_999_999), UTC(), -1);
test(DateTime(0, 12, 31, 23, 59, 59), hnsecs(1), UTC(), -9_999_999);
test(DateTime(0, 12, 31, 23, 59, 59), Duration.zero, UTC(), -10_000_000);
assertThrown!DateTimeException(SysTime(DateTime.init, hnsecs(-1), UTC()));
assertThrown!DateTimeException(SysTime(DateTime.init, seconds(1), UTC()));
static void testScope(scope ref DateTime dt, scope ref Duration d) @safe
{
auto st = SysTime(dt, d);
}
}
/++
Params:
date = The $(REF Date,std,datetime,date) to use to set this
$(LREF SysTime)'s internal std time. As
$(REF Date,std,datetime,date) has no concept of time zone, tz
is used as its time zone.
tz = The $(REF TimeZone,std,datetime,timezone) to use for this
$(LREF SysTime). If null,
$(REF LocalTime,std,datetime,timezone) will be used. The
given $(REF Date,std,datetime,date) is assumed to be in the
given time zone.
+/
this(Date date, immutable TimeZone tz = null) @safe nothrow
{
_timezone = tz is null ? LocalTime() : tz;
try
{
immutable adjustedTime = (date - Date(1, 1, 1)).total!"hnsecs";
immutable standardTime = _timezone.tzToUTC(adjustedTime);
this(standardTime, _timezone);
}
catch (Exception e)
assert(0, "Date's constructor through when it shouldn't have.");
}
@safe unittest
{
static void test(Date d, immutable TimeZone tz, long expected)
{
auto sysTime = SysTime(d, tz);
assert(sysTime._stdTime == expected);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz), format("Given Date: %s", d));
}
test(Date.init, UTC(), 0);
test(Date(1, 1, 1), UTC(), 0);
test(Date(1, 1, 2), UTC(), 864000000000);
test(Date(0, 12, 31), UTC(), -864000000000);
static void testScope(scope ref Date d) @safe
{
auto st = SysTime(d);
}
}
/++
Note:
Whereas the other constructors take in the given date/time, assume
that it's in the given time zone, and convert it to hnsecs in UTC
since midnight, January 1st, 1 A.D. UTC - i.e. std time - this
constructor takes a std time, which is specifically already in UTC,
so no conversion takes place. Of course, the various getter
properties and functions will use the given time zone's conversion
function to convert the results to that time zone, but no conversion
of the arguments to this constructor takes place.
Params:
stdTime = The number of hnsecs since midnight, January 1st, 1 A.D.
UTC.
tz = The $(REF TimeZone,std,datetime,timezone) to use for this
$(LREF SysTime). If null,
$(REF LocalTime,std,datetime,timezone) will be used.
+/
this(long stdTime, immutable TimeZone tz = null) @safe pure nothrow
{
_stdTime = stdTime;
_timezone = tz is null ? LocalTime() : tz;
}
@safe unittest
{
static void test(long stdTime, immutable TimeZone tz)
{
auto sysTime = SysTime(stdTime, tz);
assert(sysTime._stdTime == stdTime);
assert(sysTime._timezone is (tz is null ? LocalTime() : tz), format("Given stdTime: %s", stdTime));
}
foreach (stdTime; [-1234567890L, -250, 0, 250, 1235657390L])
{
foreach (tz; testTZs)
test(stdTime, tz);
}
}
/++
Params:
rhs = The $(LREF SysTime) to assign to this one.
Returns: The `this` of this `SysTime`.
+/
ref SysTime opAssign()(auto ref const(SysTime) rhs) return @safe pure nothrow scope
{
_stdTime = rhs._stdTime;
_timezone = rhs._timezone;
return this;
}
@safe unittest
{
SysTime st;
st = SysTime(DateTime(2012, 12, 21, 1, 2, 3), UTC());
assert(st == SysTime(DateTime(2012, 12, 21, 1, 2, 3), UTC()));
const other = SysTime(DateTime(19, 1, 7, 13, 14, 15), LocalTime());
st = other;
assert(st == other);
static void testScope(scope ref SysTime left, const scope SysTime right) @safe
{
left = right;
}
}
/++
Checks for equality between this $(LREF SysTime) and the given
$(LREF SysTime).
Note that the time zone is ignored. Only the internal
std times (which are in UTC) are compared.
+/
bool opEquals()(auto ref const(SysTime) rhs) @safe const pure nothrow scope
{
return _stdTime == rhs._stdTime;
}
@safe unittest
{
import std.range : chain;
assert(SysTime(DateTime.init, UTC()) == SysTime(0, UTC()));
assert(SysTime(DateTime.init, UTC()) == SysTime(0));
assert(SysTime(Date.init, UTC()) == SysTime(0));
assert(SysTime(0) == SysTime(0));
static void test(DateTime dt, immutable TimeZone tz1, immutable TimeZone tz2)
{
auto st1 = SysTime(dt);
st1.timezone = tz1;
auto st2 = SysTime(dt);
st2.timezone = tz2;
assert(st1 == st2);
}
foreach (tz1; testTZs)
{
foreach (tz2; testTZs)
{
foreach (dt; chain(testDateTimesBC, testDateTimesAD))
test(dt, tz1, tz2);
}
}
auto st = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
const cst = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
immutable ist = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
assert(st == st);
assert(st == cst);
assert(st == ist);
assert(cst == st);
assert(cst == cst);
assert(cst == ist);
assert(ist == st);
assert(ist == cst);
assert(ist == ist);
static void testScope(scope ref SysTime left, const scope SysTime right) @safe
{
assert(left == right);
assert(right == left);
}
}
/++
Compares this $(LREF SysTime) with the given $(LREF SysTime).
Time zone is irrelevant when comparing $(LREF SysTime)s.
Returns:
$(BOOKTABLE,
$(TR $(TD this < rhs) $(TD < 0))
$(TR $(TD this == rhs) $(TD 0))
$(TR $(TD this > rhs) $(TD > 0))
)
+/
int opCmp()(auto ref const(SysTime) rhs) @safe const pure nothrow scope
{
if (_stdTime < rhs._stdTime)
return -1;
if (_stdTime > rhs._stdTime)
return 1;
return 0;
}
@safe unittest
{
import std.algorithm.iteration : map;
import std.array : array;
import std.range : chain;
assert(SysTime(DateTime.init, UTC()).opCmp(SysTime(0, UTC())) == 0);
assert(SysTime(DateTime.init, UTC()).opCmp(SysTime(0)) == 0);
assert(SysTime(Date.init, UTC()).opCmp(SysTime(0)) == 0);
assert(SysTime(0).opCmp(SysTime(0)) == 0);
static void testEqual(SysTime st, immutable TimeZone tz1, immutable TimeZone tz2)
{
auto st1 = st;
st1.timezone = tz1;
auto st2 = st;
st2.timezone = tz2;
assert(st1.opCmp(st2) == 0);
}
auto sts = array(map!SysTime(chain(testDateTimesBC, testDateTimesAD)));
foreach (st; sts)
{
foreach (tz1; testTZs)
{
foreach (tz2; testTZs)
testEqual(st, tz1, tz2);
}
}
static void testCmp(SysTime st1, immutable TimeZone tz1, SysTime st2, immutable TimeZone tz2)
{
st1.timezone = tz1;
st2.timezone = tz2;
assert(st1.opCmp(st2) < 0);
assert(st2.opCmp(st1) > 0);
}
foreach (si, st1; sts)
{
foreach (st2; sts[si + 1 .. $])
{
foreach (tz1; testTZs)
{
foreach (tz2; testTZs)
testCmp(st1, tz1, st2, tz2);
}
}
}
auto st = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
const cst = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
immutable ist = SysTime(DateTime(1999, 7, 6, 12, 33, 30));
assert(st.opCmp(st) == 0);
assert(st.opCmp(cst) == 0);
assert(st.opCmp(ist) == 0);
assert(cst.opCmp(st) == 0);
assert(cst.opCmp(cst) == 0);
assert(cst.opCmp(ist) == 0);
assert(ist.opCmp(st) == 0);
assert(ist.opCmp(cst) == 0);
assert(ist.opCmp(ist) == 0);
static void testScope(scope ref SysTime left, const scope SysTime right) @safe
{
assert(left < right);
assert(right > left);
}
}
/++
Returns: A hash of the $(LREF SysTime).
+/
size_t toHash() const @nogc pure nothrow @safe scope
{
static if (is(size_t == ulong))
return _stdTime;
else
{
// MurmurHash2
enum ulong m = 0xc6a4a7935bd1e995UL;
enum ulong n = m * 16;
enum uint r = 47;
ulong k = _stdTime;
k *= m;
k ^= k >> r;
k *= m;
ulong h = n;
h ^= k;
h *= m;
return cast(size_t) h;
}
}
@safe unittest
{
assert(SysTime(0).toHash == SysTime(0).toHash);
assert(SysTime(DateTime(2000, 1, 1)).toHash == SysTime(DateTime(2000, 1, 1)).toHash);
assert(SysTime(DateTime(2000, 1, 1)).toHash != SysTime(DateTime(2000, 1, 2)).toHash);
// test that timezones aren't taken into account
assert(SysTime(0, LocalTime()).toHash == SysTime(0, LocalTime()).toHash);
assert(SysTime(0, LocalTime()).toHash == SysTime(0, UTC()).toHash);
assert(SysTime(DateTime(2000, 1, 1), LocalTime()).toHash == SysTime(DateTime(2000, 1, 1), LocalTime()).toHash);
immutable zone = new SimpleTimeZone(dur!"minutes"(60));
assert(SysTime(DateTime(2000, 1, 1, 1), zone).toHash == SysTime(DateTime(2000, 1, 1), UTC()).toHash);
assert(SysTime(DateTime(2000, 1, 1), zone).toHash != SysTime(DateTime(2000, 1, 1), UTC()).toHash);
static void testScope(scope ref SysTime st) @safe
{
auto result = st.toHash();
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
+/
@property short year() @safe const nothrow scope
{
return (cast(Date) this).year;
}
@safe unittest
{
import std.range : chain;
static void test(SysTime sysTime, long expected)
{
assert(sysTime.year == expected, format("Value given: %s", sysTime));
}
test(SysTime(0, UTC()), 1);
test(SysTime(1, UTC()), 1);
test(SysTime(-1, UTC()), 0);
foreach (year; chain(testYearsBC, testYearsAD))
{
foreach (md; testMonthDays)
{
foreach (tod; testTODs)
{
auto dt = DateTime(Date(year, md.month, md.day), tod);
foreach (tz; testTZs)
{
foreach (fs; testFracSecs)
test(SysTime(dt, fs, tz), year);
}
}
}
}
const cst = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
immutable ist = SysTime(DateTime(1999, 7, 6, 12, 30, 33));
assert(cst.year == 1999);
assert(ist.year == 1999);
static void testScope(scope ref SysTime st) @safe
{
auto result = st.year;
}
}
/++
Year of the Gregorian Calendar. Positive numbers are A.D. Non-positive
are B.C.
Params:
year = The year to set this $(LREF SysTime)'s year to.
Throws:
$(REF DateTimeException,std,datetime,date) if the new year is not
a leap year and the resulting date would be on February 29th.
+/
@property void year(int year) @safe scope
{
auto hnsecs = adjTime;
auto days = splitUnitsFromHNSecs!"days"(hnsecs) + 1;
if (hnsecs < 0)
{
hnsecs += convert!("hours", "hnsecs")(24);
--days;
}
auto date = Date(cast(int) days);
date.year = year;
immutable newDaysHNSecs = convert!("days", "hnsecs")(date.dayOfGregorianCal - 1);
adjTime = newDaysHNSecs + hnsecs;
}
///