File: DateTime.pm

package info (click to toggle)
otrs2 6.0.32-6
  • links: PTS
  • area: non-free
  • in suites: bullseye
  • size: 197,336 kB
  • sloc: perl: 1,003,018; javascript: 75,060; xml: 70,883; php: 51,819; sql: 22,361; sh: 379; makefile: 51
file content (2018 lines) | stat: -rw-r--r-- 60,367 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
# --
# Copyright (C) 2001-2021 OTRS AG, https://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see https://www.gnu.org/licenses/gpl-3.0.txt.
# --

package Kernel::System::DateTime;
## nofilter(TidyAll::Plugin::OTRS::Perl::Time)
## nofilter(TidyAll::Plugin::OTRS::Perl::Translatable)

use strict;
use warnings;

use Exporter qw(import);
our %EXPORT_TAGS = (    ## no critic
    all => [
        'OTRSTimeZoneGet',
        'SystemTimeZoneGet',
        'TimeZoneList',
        'UserDefaultTimeZoneGet',
    ],
);
Exporter::export_ok_tags('all');

use DateTime;
use DateTime::TimeZone;
use Scalar::Util qw( looks_like_number );
use Kernel::System::VariableCheck qw( IsArrayRefWithData IsHashRefWithData );

our %ObjectManagerFlags = (
    NonSingleton            => 1,
    AllowConstructorFailure => 1,
);

our @ObjectDependencies = (
    'Kernel::Config',
    'Kernel::System::Main',
    'Kernel::System::Log',
);

our $Locale = DateTime::Locale->load('en_US');

use overload
    '>'        => \&_OpIsNewerThan,
    '<'        => \&_OpIsOlderThan,
    '>='       => \&_OpIsNewerThanOrEquals,
    '<='       => \&_OpIsOlderThanOrEquals,
    '=='       => \&_OpEquals,
    '!='       => \&_OpNotEquals,
    'fallback' => 1;

=head1 NAME

Kernel::System::DateTime - Handles date and time calculations.

=head1 DESCRIPTION

Handles date and time calculations.

=head1 PUBLIC INTERFACE

=head2 new()

Creates a DateTime object. Do not use new() directly, instead use the object manager:

    # Create an object with current date and time
    # within time zone set in SysConfig OTRSTimeZone:
    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime'
    );

    # Create an object with current date and time
    # within a certain time zone:
    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            TimeZone => 'Europe/Berlin',        # optional, TimeZone name.
        }
    );

    # Create an object with a specific date and time:
    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            Year     => 2016,
            Month    => 1,
            Day      => 22,
            Hour     => 12,                     # optional, defaults to 0
            Minute   => 35,                     # optional, defaults to 0
            Second   => 59,                     # optional, defaults to 0
            TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
        }
    );

    # Create an object from an epoch timestamp. These timestamps are always UTC/GMT,
    # hence time zone will automatically be set to UTC.
    #
    # If parameter Epoch is present, all other parameters will be ignored.
    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            Epoch => 1453911685,
        }
    );

    # Create an object from a date/time string.
    #
    # If parameter String is given, Year, Month, Day, Hour, Minute and Second will be ignored
    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            String   => '2016-08-14 22:45:00',
            TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
        }
    );

    # Following formats for parameter String are supported:
    #
    #   yyyy-mm-dd hh:mm:ss
    #   yyyy-mm-dd hh:mm                # sets second to 0
    #   yyyy-mm-dd                      # sets hour, minute and second to 0
    #   yyyy-mm-ddThh:mm:ss+tt:zz
    #   yyyy-mm-ddThh:mm:ss+ttzz
    #   yyyy-mm-ddThh:mm:ss-tt:zz
    #   yyyy-mm-ddThh:mm:ss-ttzz
    #   yyyy-mm-ddThh:mm:ss [timezone]  # time zone will be deduced from an optional string
    #   yyyy-mm-ddThh:mm:ss[timezone]   # i.e. 2018-04-20T07:37:10UTC

=cut

sub new {
    my ( $Type, %Param ) = @_;

    # allocate new hash for object
    my $Self = {};
    bless( $Self, $Type );

    # CPAN DateTime: only use English descriptions and abbreviations internally.
    #   This has nothing to do with the user's locale settings in OTRS.
    $Self->{Locale} = $Locale;

    # Use private parameter to pass in an already created CPANDateTimeObject (used)
    #   by the Clone() method).
    if ( $Param{_CPANDateTimeObject} ) {
        $Self->{CPANDateTimeObject} = $Param{_CPANDateTimeObject};
        return $Self;
    }

    # Create the CPAN/Perl DateTime object.
    my $CPANDateTimeObject = $Self->_CPANDateTimeObjectCreate(%Param);

    if ( ref $CPANDateTimeObject ne 'DateTime' ) {

        # Add debugging information.
        my $Parameters = $Kernel::OM->Get('Kernel::System::Main')->Dump(
            \%Param,
        );

        # Remove $VAR1 =
        $Parameters =~ s{ \s* \$VAR1 \s* = \s* \{}{}xms;

        # Remove closing brackets.
        $Parameters =~ s{\}\s+\{}{\{}xms;
        $Parameters =~ s{\};\s*$}{}xms;

        # Replace new lines with spaces.
        $Parameters =~ s{\n}{ }gsmx;

        # Replace multiple spaces with one.
        $Parameters =~ s{\s+}{ }gsmx;

        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => "Error creating DateTime object ($Parameters).",
        );

        return;
    }

    $Self->{CPANDateTimeObject} = $CPANDateTimeObject;
    return $Self;
}

=head2 Get()

Returns hash ref with the date, time and time zone values of this object.

    my $DateTimeSettings = $DateTimeObject->Get();

Returns:

    my $DateTimeSettings = {
        Year      => 2016,
        Month     => 1,         # starting at 1
        Day       => 22,
        Hour      => 16,
        Minute    => 35,
        Second    => 59,
        DayOfWeek => 5,         # starting with 1 for Monday, ending with 7 for Sunday
        TimeZone  => 'Europe/Berlin',
    };

=cut

sub Get {
    my ( $Self, %Param ) = @_;

    my $Values = {
        Year      => $Self->{CPANDateTimeObject}->year(),
        Month     => $Self->{CPANDateTimeObject}->month(),
        MonthAbbr => $Self->{CPANDateTimeObject}->month_abbr(),
        Day       => $Self->{CPANDateTimeObject}->day(),
        Hour      => $Self->{CPANDateTimeObject}->hour(),
        Minute    => $Self->{CPANDateTimeObject}->minute(),
        Second    => $Self->{CPANDateTimeObject}->second(),
        DayOfWeek => $Self->{CPANDateTimeObject}->day_of_week(),
        DayAbbr   => $Self->{CPANDateTimeObject}->day_abbr(),
        TimeZone  => $Self->{CPANDateTimeObject}->time_zone_long_name(),
    };

    return $Values;
}

=head2 Set()

Sets date and time values of this object. You have to give at least one parameter. Only given values will be changed.
Note that the resulting date and time have to be valid. On validation error, the current date and time of the object
won't be changed.

Note that in order to change the time zone, you have to use method C<L</ToTimeZone()>>.

    # Setting values by hash:
    my $Success = $DateTimeObject->Set(
        Year     => 2016,
        Month    => 1,
        Day      => 22,
        Hour     => 16,
        Minute   => 35,
        Second   => 59,
    );

    # Settings values by date/time string:
    my $Success = $DateTimeObject->Set( String => '2016-02-25 20:34:01' );

If parameter C<String> is present, all other parameters will be ignored. Please see C<L</new()>> for the list of
supported string formats.

Returns:

   $Success = 1;    # On success, or false otherwise.

=cut

sub Set {
    my ( $Self, %Param ) = @_;

    if ( defined $Param{String} ) {
        my $DateTimeHash = $Self->_StringToHash( String => $Param{String} );
        return if !$DateTimeHash;

        %Param = %{$DateTimeHash};
    }

    my @DateTimeParams = qw ( Year Month Day Hour Minute Second );

    # Check given parameters
    my $ParamGiven;
    DATETIMEPARAM:
    for my $DateTimeParam (@DateTimeParams) {
        next DATETIMEPARAM if !defined $Param{$DateTimeParam};

        $ParamGiven = 1;
        last DATETIMEPARAM;
    }

    if ( !$ParamGiven ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => 'Missing at least one parameter.',
        );
        return;
    }

    # Validate given values by using the current settings + the given ones.
    my $CurrentValues = $Self->Get();
    DATETIMEPARAM:
    for my $DateTimeParam (@DateTimeParams) {
        next DATETIMEPARAM if !defined $Param{$DateTimeParam};

        $CurrentValues->{$DateTimeParam} = $Param{$DateTimeParam};
    }

    # Create a new DateTime object with the new/added values
    my $CPANDateTimeParams = $Self->_ToCPANDateTimeParamNames( %{$CurrentValues} );

    # Delete parameters that are not allowed for set method
    delete $CPANDateTimeParams->{time_zone};

    my $Result;
    eval {
        $Result = $Self->{CPANDateTimeObject}->set( %{$CPANDateTimeParams} );
    };

    return $Result;
}

=head2 Add()

Adds duration or working time to date and time of this object. You have to give at least one of the valid parameters.
On error, the current date and time of this object won't be changed.

    my $Success = $DateTimeObject->Add(
        Years         => 1,
        Months        => 2,
        Weeks         => 4,
        Days          => 34,
        Hours         => 2,
        Minutes       => 5,
        Seconds       => 459,

        # Calculate "destination date" by adding given time values as
        # working time. Note that for adding working time,
        # only parameters Seconds, Minutes, Hours and Days are allowed.
        AsWorkingTime => 0, # set to 1 to add given values as working time

        # Calendar to use for working time calculations, optional
        Calendar => 9,
    );

Returns:

    $Success = 1;    # On success, or false otherwise.

=cut

sub Add {
    my ( $Self, %Param ) = @_;

    #
    # Check parameters
    #
    my @DateTimeParams = qw ( Years Months Weeks Days Hours Minutes Seconds );
    @DateTimeParams = qw( Days Hours Minutes Seconds ) if $Param{AsWorkingTime};

    # Check for needed parameters
    my $ParamsGiven = 0;
    my $ParamsValid = 1;
    DATETIMEPARAM:
    for my $DateTimeParam (@DateTimeParams) {
        next DATETIMEPARAM if !defined $Param{$DateTimeParam};

        if ( !looks_like_number( $Param{$DateTimeParam} ) ) {
            $ParamsValid = 0;
            last DATETIMEPARAM;
        }

        # negative values are not allowed when calculating working time
        if ( int $Param{$DateTimeParam} < 0 && $Param{AsWorkingTime} ) {
            $ParamsValid = 0;
            last DATETIMEPARAM;
        }

        $ParamsGiven = 1;
    }

    if ( !$ParamsGiven || !$ParamsValid ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => 'Missing or invalid date/time parameter(s).',
        );
        return;
    }

    # Check for not allowed parameters
    my %AllowedParams = map { $_ => 1 } @DateTimeParams;
    $AllowedParams{AsWorkingTime} = 1;
    if ( $Param{AsWorkingTime} ) {
        $AllowedParams{Calendar} = 1;
    }

    for my $Param ( sort keys %Param ) {
        if ( !$AllowedParams{$Param} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Parameter $Param is not allowed.",
            );
            return;
        }
    }

    # NOTE: For performance reasons, the following code for calculating date and time
    # works directly with the CPAN DateTime object instead of methods of Kernel::System::DateTime.

    #
    # Working time calculation
    #
    if ( $Param{AsWorkingTime} ) {

        # Combine time parameters to seconds
        my $RemainingSeconds = 0;
        if ( defined $Param{Seconds} ) {
            $RemainingSeconds += int $Param{Seconds};
        }
        if ( defined $Param{Minutes} ) {
            $RemainingSeconds += int $Param{Minutes} * 60;
        }
        if ( defined $Param{Hours} ) {
            $RemainingSeconds += int $Param{Hours} * 60 * 60;
        }
        if ( defined $Param{Days} ) {
            $RemainingSeconds += int $Param{Days} * 60 * 60 * 24;
        }

        return if !$RemainingSeconds;

        # Backup current date/time to be able to revert to it in case of failure
        my $OriginalDateTimeObject = $Self->{CPANDateTimeObject}->clone();

        my $TimeZone = $OriginalDateTimeObject->time_zone();

        # Get working and vacation times, use calendar if given
        my $ConfigObject            = $Kernel::OM->Get('Kernel::Config');
        my $TimeWorkingHours        = $ConfigObject->Get('TimeWorkingHours');
        my $TimeVacationDays        = $ConfigObject->Get('TimeVacationDays');
        my $TimeVacationDaysOneTime = $ConfigObject->Get('TimeVacationDaysOneTime');
        if (
            $Param{Calendar}
            && $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} . "Name" )
            )
        {
            $TimeWorkingHours        = $ConfigObject->Get( "TimeWorkingHours::Calendar" . $Param{Calendar} );
            $TimeVacationDays        = $ConfigObject->Get( "TimeVacationDays::Calendar" . $Param{Calendar} );
            $TimeVacationDaysOneTime = $ConfigObject->Get(
                "TimeVacationDaysOneTime::Calendar" . $Param{Calendar}
            );

            # Switch to time zone of calendar
            $TimeZone = $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} )
                || $Self->OTRSTimeZoneGet();

            # Use Kernel::System::DateTime's ToTimeZone() here because of error handling
            # and because performance is irrelevant at this point.
            if ( !$Self->ToTimeZone( TimeZone => $TimeZone ) ) {
                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    Priority => 'error',
                    Message  => "Error setting time zone $TimeZone.",
                );

                return;
            }
        }

        # If there are for some reason no working hours configured, stop here
        # to prevent failing via loop protection below.
        my $WorkingHoursConfigured;
        WORKINGHOURCONFIGDAY:
        for my $WorkingHourConfigDay ( sort keys %{$TimeWorkingHours} ) {
            if ( IsArrayRefWithData( $TimeWorkingHours->{$WorkingHourConfigDay} ) ) {
                $WorkingHoursConfigured = 1;
                last WORKINGHOURCONFIGDAY;
            }
        }
        return 1 if !$WorkingHoursConfigured;

        # Convert $TimeWorkingHours into Hash
        my %TimeWorkingHours;
        for my $DayName ( sort keys %{$TimeWorkingHours} ) {
            $TimeWorkingHours{$DayName} = { map { $_ => 1 } @{ $TimeWorkingHours->{$DayName} } };
        }

        # Protection for endless loop
        my $LoopStartTime = time();
        LOOP:
        while ( $RemainingSeconds > 0 ) {

            # Fail if this loop takes longer than 5 seconds
            if ( time() - $LoopStartTime > 5 ) {

                # Reset this object to original date/time.
                $Self->{CPANDateTimeObject} = $OriginalDateTimeObject->clone();

                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    Priority => 'error',
                    Message  => 'Adding working time took too long, aborting.',
                );

                return;
            }

            my $Year    = $Self->{CPANDateTimeObject}->year();
            my $Month   = $Self->{CPANDateTimeObject}->month();
            my $Day     = $Self->{CPANDateTimeObject}->day();
            my $DayName = $Self->{CPANDateTimeObject}->day_abbr();
            my $Hour    = $Self->{CPANDateTimeObject}->hour();
            my $Minute  = $Self->{CPANDateTimeObject}->minute();
            my $Second  = $Self->{CPANDateTimeObject}->second();

            # Check working times and vacation days
            my $IsWorkingDay = !$TimeVacationDays->{$Month}->{$Day}
                && !$TimeVacationDaysOneTime->{$Year}->{$Month}->{$Day}
                && exists $TimeWorkingHours->{$DayName}
                && keys %{ $TimeWorkingHours{$DayName} };

            # On start of day check if whole day can be processed in one chunk
            # instead of hour by hour (performance reasons).
            if ( !$Hour && !$Minute && !$Second ) {

                # The following code is slightly faster than using CPAN DateTime's add(),
                # presumably because add() always creates a DateTime::Duration object.
                my $Epoch = $Self->{CPANDateTimeObject}->epoch();
                $Epoch += 60 * 60 * 24;

                my $NextDayDateTimeObject = DateTime->from_epoch(
                    epoch     => $Epoch,
                    time_zone => $TimeZone,
                    locale    => $Self->{Locale},
                );

                # Only handle days with exactly 24 hours here
                if (
                    !$NextDayDateTimeObject->hour()
                    && !$NextDayDateTimeObject->minute()
                    && !$NextDayDateTimeObject->second()
                    && $NextDayDateTimeObject->day() != $Day
                    )
                {
                    my $FullDayProcessed = 1;

                    if ($IsWorkingDay) {
                        my $WorkingHours   = keys %{ $TimeWorkingHours{$DayName} };
                        my $WorkingSeconds = $WorkingHours * 60 * 60;

                        if ( $RemainingSeconds > $WorkingSeconds ) {
                            $RemainingSeconds -= $WorkingSeconds;
                        }
                        else {
                            $FullDayProcessed = 0;
                        }
                    }

                    # Move forward 24 hours if full day has been processed
                    if ($FullDayProcessed) {

                        # Time implicitly set to 0
                        $Self->{CPANDateTimeObject}->set(
                            year  => $NextDayDateTimeObject->year(),
                            month => $NextDayDateTimeObject->month(),
                            day   => $NextDayDateTimeObject->day(),
                        );

                        next LOOP;
                    }
                }
            }

            # Calculate remaining seconds of the current hour
            my $SecondsOfCurrentHour = ( $Minute * 60 ) + $Second;
            my $SecondsToAdd         = ( 60 * 60 ) - $SecondsOfCurrentHour;

            if ( $IsWorkingDay && $TimeWorkingHours{$DayName}->{$Hour} ) {
                $SecondsToAdd = $RemainingSeconds if $SecondsToAdd > $RemainingSeconds;
                $RemainingSeconds -= $SecondsToAdd;
            }

            # The following code is slightly faster than using CPAN DateTime's add(),
            # presumably because add() always creates a DateTime::Duration object.
            my $Epoch = $Self->{CPANDateTimeObject}->epoch();
            $Epoch += $SecondsToAdd;

            $Self->{CPANDateTimeObject} = DateTime->from_epoch(
                epoch     => $Epoch,
                time_zone => $TimeZone,
                locale    => $Self->{Locale},
            );
        }

        # Return to original time zone, might have been changed by calendar
        $Self->{CPANDateTimeObject}->set_time_zone( $OriginalDateTimeObject->time_zone() );

        return 1;
    }

    #
    # "Normal" date/time calculation
    #

    # Calculations are only made in UTC/floating time zone to prevent errors with times that
    # would not exist in the given time zone (e. g. on/around daylight saving time switch).
    # CPAN DateTime fails if adding days, months or years which would result in a non-existing
    # time in the given time zone. Converting it to UTC and back has the desired effect.
    #
    # Also see http://stackoverflow.com/questions/18489927/a-day-without-midnight
    my $TimeZone = $Self->{CPANDateTimeObject}->time_zone();
    $Self->{CPANDateTimeObject}->set_time_zone('UTC');

    # Convert to floating time zone to get rid of leap seconds which can lead to times like 23:59:61
    $Self->{CPANDateTimeObject}->set_time_zone('floating');

    # Add duration
    my $DurationParameters = $Self->_ToCPANDateTimeParamNames(%Param);
    eval {
        $Self->{CPANDateTimeObject}->add( %{$DurationParameters} );
    };

    # Store possible error before it might get lost by call to ToTimeZone
    my $Error = $@;

    # First convert floating time zone back to UTC and from there to the original time zone
    $Self->{CPANDateTimeObject}->set_time_zone('UTC');
    $Self->{CPANDateTimeObject}->set_time_zone($TimeZone);

    return if $Error;

    return 1;
}

=head2 Subtract()

Subtracts duration from date and time of this object. You have to give at least one of the valid parameters. On
validation error, the current date and time of this object won't be changed.

    my $Success = $DateTimeObject->Subtract(
        Years     => 1,
        Months    => 2,
        Weeks     => 4,
        Days      => 34,
        Hours     => 2,
        Minutes   => 5,
        Seconds   => 459,
    );

Returns:

    $Success =  1;  # On success, or false otherwise.

=cut

sub Subtract {
    my ( $Self, %Param ) = @_;

    my @DateTimeParams = qw ( Years Months Weeks Days Hours Minutes Seconds );

    # Check for needed parameters
    my $ParamsGiven = 0;
    my $ParamsValid = 1;
    DATETIMEPARAM:
    for my $DateTimeParam (@DateTimeParams) {
        next DATETIMEPARAM if !defined $Param{$DateTimeParam};

        if ( !looks_like_number( $Param{$DateTimeParam} ) ) {
            $ParamsValid = 0;
            last DATETIMEPARAM;
        }

        # negative values are not allowed when calculating working time
        if ( int $Param{$DateTimeParam} < 0 && $Param{AsWorkingTime} ) {
            $ParamsValid = 0;
            last DATETIMEPARAM;
        }

        $ParamsGiven = 1;
    }

    if ( !$ParamsGiven || !$ParamsValid ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => 'Missing or invalid date/time parameter(s).',
        );
        return;
    }

    # Check for not allowed parameters
    my %AllowedParams = map { $_ => 1 } @DateTimeParams;
    $AllowedParams{AsWorkingTime} = 1;
    if ( $Param{AsWorkingTime} ) {
        $AllowedParams{Calendar} = 1;
    }

    for my $Param ( sort keys %Param ) {
        if ( !$AllowedParams{$Param} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Parameter $Param is not allowed.",
            );
            return;
        }
    }

    # Calculations are only made in UTC/floating time zone to prevent errors with times that
    # would not exist in the given time zone (e. g. on/around daylight saving time switch).
    my $DateTimeValues = $Self->Get();
    $Self->ToTimeZone( TimeZone => 'UTC' );

    # Convert to floating time zone to get rid of leap seconds which can lead to times like 23:59:61
    $Self->{CPANDateTimeObject}->set_time_zone('floating');

    # Subtract duration
    my $DurationParameters = $Self->_ToCPANDateTimeParamNames(%Param);
    eval {
        $Self->{CPANDateTimeObject}->subtract( %{$DurationParameters} );
    };

    # Store possible error before it might get lost by call to ToTimeZone
    my $Error = $@;

    # First convert floating time zone back to UTC and from there to the original time zone
    $Self->{CPANDateTimeObject}->set_time_zone('UTC');
    $Self->ToTimeZone( TimeZone => $DateTimeValues->{TimeZone} );

    return if $@;

    return 1;
}

=head2 Delta()

Calculates delta between this and another DateTime object. Optionally calculates the working time between the two.

    my $Delta = $DateTimeObject->Delta( DateTimeObject => $AnotherDateTimeObject );

Note that the returned values are always positive. Use the comparison methods to see if a date is newer/older/equal.

    # Calculate "working time"
    ForWorkingTime => 0, # set to 1 to calculate working time between the two DateTime objects

    # Calendar to use for working time calculations, optional
    Calendar => 9,

Returns:

    my $Delta = {
        Years           => 1,           # Set to 0 if working time was calculated
        Months          => 2,           # Set to 0 if working time was calculated
        Weeks           => 4,           # Set to 0 if working time was calculated
        Days            => 34,          # Set to 0 if working time was calculated
        Hours           => 2,
        Minutes         => 5,
        Seconds         => 459,
        AbsoluteSeconds => 42084759,    # complete delta in seconds
    };

=cut

sub Delta {
    my ( $Self, %Param ) = @_;

    if (
        !defined $Param{DateTimeObject}
        || ref $Param{DateTimeObject} ne ref $Self
        )
    {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => "Missing or invalid parameter DateTimeObject.",
        );
        return;
    }

    my $Delta = {
        Years           => 0,
        Months          => 0,
        Weeks           => 0,
        Days            => 0,
        Hours           => 0,
        Minutes         => 0,
        Seconds         => 0,
        AbsoluteSeconds => 0,
    };

    #
    # Calculate delta for working time
    #
    if ( $Param{ForWorkingTime} ) {

        # NOTE: For performance reasons, the following code for calculating the working time
        # works directly with the CPAN DateTime object instead of Kernel::System::DateTime.

        # Clone StartDateTime object because it will be changed while calculating
        # but the original object must not be changed.
        my $StartDateTimeObject = $Self->{CPANDateTimeObject}->clone();
        my $TimeZone            = $StartDateTimeObject->time_zone();

        # Get working and vacation times, use calendar if given
        my $ConfigObject            = $Kernel::OM->Get('Kernel::Config');
        my $TimeWorkingHours        = $ConfigObject->Get('TimeWorkingHours');
        my $TimeVacationDays        = $ConfigObject->Get('TimeVacationDays');
        my $TimeVacationDaysOneTime = $ConfigObject->Get('TimeVacationDaysOneTime');
        if (
            $Param{Calendar}
            && $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} . "Name" )
            )
        {
            $TimeWorkingHours        = $ConfigObject->Get( "TimeWorkingHours::Calendar" . $Param{Calendar} );
            $TimeVacationDays        = $ConfigObject->Get( "TimeVacationDays::Calendar" . $Param{Calendar} );
            $TimeVacationDaysOneTime = $ConfigObject->Get(
                "TimeVacationDaysOneTime::Calendar" . $Param{Calendar}
            );

            # switch to time zone of calendar
            $TimeZone = $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} )
                || $Self->OTRSTimeZoneGet();

            eval {
                $StartDateTimeObject->set_time_zone($TimeZone);
            };

            if ($@) {
                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    Priority => 'error',
                    Message  => "Error setting time zone $TimeZone for start DateTime object.",
                );

                return;
            }
        }

        # If there are for some reason no working hours configured, stop here
        # to prevent failing via loop protection below.
        my $WorkingHoursConfigured;
        WORKINGHOURCONFIGDAY:
        for my $WorkingHourConfigDay ( sort keys %{$TimeWorkingHours} ) {
            if ( IsArrayRefWithData( $TimeWorkingHours->{$WorkingHourConfigDay} ) ) {
                $WorkingHoursConfigured = 1;
                last WORKINGHOURCONFIGDAY;
            }
        }
        return $Delta if !$WorkingHoursConfigured;

        # Convert $TimeWorkingHours into Hash
        my %TimeWorkingHours;
        for my $DayName ( sort keys %{$TimeWorkingHours} ) {
            $TimeWorkingHours{$DayName} = { map { $_ => 1 } @{ $TimeWorkingHours->{$DayName} } };
        }

        my $StartTime   = $StartDateTimeObject->epoch();
        my $StopTime    = $Param{DateTimeObject}->{CPANDateTimeObject}->epoch();
        my $WorkingTime = 0;

        # Protection for endless loop
        my $LoopStartTime = time();
        LOOP:
        while ( $StartTime < $StopTime ) {

            # Fail if this loop takes longer than 5 seconds
            if ( time() - $LoopStartTime > 5 ) {
                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    Priority => 'error',
                    Message  => 'Delta calculation of working time took too long, aborting.',
                );

                return;
            }

            my $RemainingSeconds = $StopTime - $StartTime;

            my $Year    = $StartDateTimeObject->year();
            my $Month   = $StartDateTimeObject->month();
            my $Day     = $StartDateTimeObject->day();
            my $DayName = $StartDateTimeObject->day_abbr();
            my $Hour    = $StartDateTimeObject->hour();
            my $Minute  = $StartDateTimeObject->minute();
            my $Second  = $StartDateTimeObject->second();

            # Check working times and vacation days
            my $IsWorkingDay = !$TimeVacationDays->{$Month}->{$Day}
                && !$TimeVacationDaysOneTime->{$Year}->{$Month}->{$Day}
                && exists $TimeWorkingHours->{$DayName}
                && keys %{ $TimeWorkingHours{$DayName} };

            # On start of day check if whole day can be processed in one chunk
            # instead of hour by hour (performance reasons).
            if ( !$Hour && !$Minute && !$Second ) {

                # The following code is slightly faster than using CPAN DateTime's add(),
                # presumably because add() always creates a DateTime::Duration object.
                my $Epoch = $StartDateTimeObject->epoch();
                $Epoch += 60 * 60 * 24;

                my $NextDayDateTimeObject = DateTime->from_epoch(
                    epoch     => $Epoch,
                    time_zone => $TimeZone,
                    locale    => $Self->{Locale},
                );

                # Only handle days with exactly 24 hours here
                if (
                    !$NextDayDateTimeObject->hour()
                    && !$NextDayDateTimeObject->minute()
                    && !$NextDayDateTimeObject->second()
                    && $NextDayDateTimeObject->day() != $Day
                    && $RemainingSeconds > 60 * 60 * 24
                    )
                {
                    my $FullDayProcessed = 1;

                    if ($IsWorkingDay) {
                        my $WorkingHours   = keys %{ $TimeWorkingHours{$DayName} };
                        my $WorkingSeconds = $WorkingHours * 60 * 60;

                        if ( $RemainingSeconds > $WorkingSeconds ) {
                            $WorkingTime += $WorkingSeconds;
                        }
                        else {
                            $FullDayProcessed = 0;
                        }
                    }

                    # Move forward 24 hours if full day has been processed
                    if ($FullDayProcessed) {

                        # Time implicitly set to 0
                        $StartDateTimeObject->set(
                            year  => $NextDayDateTimeObject->year(),
                            month => $NextDayDateTimeObject->month(),
                            day   => $NextDayDateTimeObject->day(),
                        );

                        $StartTime = $Epoch;

                        next LOOP;
                    }
                }
            }

            # Calculate remaining seconds of the current hour
            my $SecondsOfCurrentHour = ( $Minute * 60 ) + $Second;
            my $SecondsToAdd         = ( 60 * 60 ) - $SecondsOfCurrentHour;

            if ( $IsWorkingDay && $TimeWorkingHours{$DayName}->{$Hour} ) {
                $SecondsToAdd = $RemainingSeconds if $SecondsToAdd > $RemainingSeconds;
                $WorkingTime += $SecondsToAdd;
            }

            # The following code is slightly faster than using CPAN DateTime's add(),
            # presumably because add() always creates a DateTime::Duration object.
            my $Epoch = $StartDateTimeObject->epoch();
            $Epoch += $SecondsToAdd;

            $StartDateTimeObject = DateTime->from_epoch(
                epoch     => $Epoch,
                time_zone => $TimeZone,
                locale    => $Self->{Locale},
            );

            $StartTime = $Epoch;
        }

        # Set values for delta
        my $RemainingWorkingTime = $WorkingTime;

        $Delta->{Hours} = int $RemainingWorkingTime / ( 60 * 60 );
        $RemainingWorkingTime -= $Delta->{Hours} * 60 * 60;

        $Delta->{Minutes} = int $RemainingWorkingTime / 60;
        $RemainingWorkingTime -= $Delta->{Minutes} * 60;

        $Delta->{Seconds} = $RemainingWorkingTime;
        $RemainingWorkingTime = 0;

        $Delta->{AbsoluteSeconds} = $WorkingTime;

        return $Delta;
    }

    #
    # Calculate delta for "normal" date/time
    #
    my $DeltaDuration = $Self->{CPANDateTimeObject}->subtract_datetime(
        $Param{DateTimeObject}->{CPANDateTimeObject}
    );

    $Delta->{Years}   = $DeltaDuration->years();
    $Delta->{Months}  = $DeltaDuration->months();
    $Delta->{Weeks}   = $DeltaDuration->weeks();
    $Delta->{Days}    = $DeltaDuration->days();
    $Delta->{Hours}   = $DeltaDuration->hours();
    $Delta->{Minutes} = $DeltaDuration->minutes();
    $Delta->{Seconds} = $DeltaDuration->seconds();

    # Absolute seconds
    $DeltaDuration = $Self->{CPANDateTimeObject}->subtract_datetime_absolute(
        $Param{DateTimeObject}->{CPANDateTimeObject}
    );

    $Delta->{AbsoluteSeconds} = $DeltaDuration->seconds();

    return $Delta;
}

=head2 Compare()

Compares dates and returns a value suitable for using Perl's sort function (-1, 0, 1).

    my $Result = $DateTimeObject->Compare( DateTimeObject => $AnotherDateTimeObject );

You can also use this as a function for Perl's sort:

    my @SortedDateTimeObjects = sort { $a->Compare( DateTimeObject => $b ); } @UnsortedDateTimeObjects:

Returns:

    $Result = -1;       # if date/time of this object < date/time of given object
    $Result = 0;        # if date/time are equal
    $Result = 1:        # if date/time of this object > date/time of given object

=cut

sub Compare {
    my ( $Self, %Param ) = @_;

    if (
        !defined $Param{DateTimeObject}
        || ref $Param{DateTimeObject} ne ref $Self
        )
    {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => "Missing or invalid parameter DateTimeObject.",
        );
        return;
    }

    my $Result;
    eval {
        $Result = DateTime->compare(
            $Self->{CPANDateTimeObject},
            $Param{DateTimeObject}->{CPANDateTimeObject}
        );
    };

    return $Result;
}

=head2 ToTimeZone()

Converts the date and time of this object to the given time zone.

    my $Success = $DateTimeObject->ToTimeZone(
        TimeZone => 'Europe/Berlin',
    );

Returns:

    $Success = 1;   # success, or false otherwise.

=cut

sub ToTimeZone {
    my ( $Self, %Param ) = @_;

    for my $RequiredParam (qw( TimeZone )) {
        if ( !defined $Param{$RequiredParam} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Missing parameter $RequiredParam.",
            );
            return;
        }
    }

    eval {
        $Self->{CPANDateTimeObject}->set_time_zone( $Param{TimeZone} );
    };

    return if $@;

    return 1;
}

=head2 ToOTRSTimeZone()

Converts the date and time of this object to the data storage time zone.

    my $Success = $DateTimeObject->ToOTRSTimeZone();

Returns:

    $Success = 1;   # success, or false otherwise.

=cut

sub ToOTRSTimeZone {
    my ( $Self, %Param ) = @_;

    return $Self->ToTimeZone( TimeZone => $Self->OTRSTimeZoneGet() );
}

=head2 Validate()

Checks if given date, time and time zone would result in a valid date.

    my $IsValid = $DateTimeObject->Validate(
        Year     => 2016,
        Month    => 1,
        Day      => 22,
        Hour     => 16,
        Minute   => 35,
        Second   => 59,
        TimeZone => 'Europe/Berlin',
    );

Returns:

    $IsValid = 1;   # if date/time is valid, or false otherwise.

=cut

sub Validate {
    my ( $Self, %Param ) = @_;

    my @DateTimeParams = qw ( Year Month Day Hour Minute Second TimeZone );
    for my $RequiredDateTimeParam (@DateTimeParams) {
        if ( !defined $Param{$RequiredDateTimeParam} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Missing parameter $RequiredDateTimeParam.",
            );
            return;
        }
    }

    my $DateTimeObject = $Self->_CPANDateTimeObjectCreate(%Param);
    return if !$DateTimeObject;

    return 1;
}

=head2 Format()

Returns the date/time as string formatted according to format given.

See L<http://search.cpan.org/~drolsky/DateTime-1.21/lib/DateTime.pm#strftime_Patterns> for supported formats.

Short overview of essential formatting options:

    %Y or %{year}: four digit year

    %m: month with leading zero
    %{month}: month without leading zero

    %d: day of month with leading zero
    %{day}: day of month without leading zero

    %H: 24 hour with leading zero
    %{hour}: 24 hour without leading zero

    %l: 12 hour with leading zero
    %{hour_12}: 12 hour without leading zero

    %M: minute with leading zero
    %{minute}: minute without leading zero

    %S: second with leading zero
    %{second}: second without leading zero

    %{time_zone_long_name}: Time zone, e. g. 'Europe/Berlin'

    %{epoch}: Seconds since the epoch (OS specific)
    %{offset}: Offset in seconds to GMT/UTC

    my $DateTimeString = $DateTimeObject->Format( Format => '%Y-%m-%d %H:%M:%S' );

Returns:

    my $String = '2016-01-22 18:07:23';

=cut

sub Format {
    my ( $Self, %Param ) = @_;

    for my $RequiredParam (qw( Format )) {
        if ( !defined $Param{$RequiredParam} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Missing parameter $RequiredParam.",
            );

            return;
        }
    }

    return $Self->{CPANDateTimeObject}->strftime( $Param{Format} );
}

=head2 ToEpoch()

Returns date/time as seconds since the epoch.

    my $Epoch = $DateTimeObject->ToEpoch();

Returns e. g.:

    my $Epoch = 1454420017;

=cut

sub ToEpoch {
    my ( $Self, %Param ) = @_;

    return $Self->{CPANDateTimeObject}->epoch();
}

=head2 ToString()

Returns date/time as string.

    my $DateTimeString = $DateTimeObject->ToString();

Returns e. g.:

    $DateTimeString = '2016-01-31 14:05:45'

=cut

sub ToString {
    my ( $Self, %Param ) = @_;

    return $Self->Format( Format => '%Y-%m-%d %H:%M:%S' );
}

=head2 ToEmailTimeStamp()

Returns the date/time of this object as time stamp in RFC 2822 format to be used in email headers.

    my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

    # Typical usage:
    # You want to have the date/time of OTRS + its UTC offset, so:
    my $DateTimeObject = $Kernel::OM->Create('Kernel::System::DateTime');
    my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

    # If you already have a DateTime object, possibly in another time zone:
    $DateTimeObject->ToOTRSTimeZone();
    my $MailTimeStamp = $DateTimeObject->ToEmailTimeStamp();

Returns:

    my $String = 'Wed, 2 Sep 2014 16:30:57 +0200';

=cut

sub ToEmailTimeStamp {
    my ( $Self, %Param ) = @_;

    # According to RFC 2822, section 3.3

    # The date and time-of-day SHOULD express local time.
    #
    # The zone specifies the offset from Coordinated Universal Time (UTC,
    # formerly referred to as "Greenwich Mean Time") that the date and
    # time-of-day represent.  The "+" or "-" indicates whether the
    # time-of-day is ahead of (i.e., east of) or behind (i.e., west of)
    # Universal Time.  The first two digits indicate the number of hours
    # difference from Universal Time, and the last two digits indicate the
    # number of minutes difference from Universal Time.  (Hence, +hhmm
    # means +(hh * 60 + mm) minutes, and -hhmm means -(hh * 60 + mm)
    # minutes).  The form "+0000" SHOULD be used to indicate a time zone at
    # Universal Time.  Though "-0000" also indicates Universal Time, it is
    # used to indicate that the time was generated on a system that may be
    # in a local time zone other than Universal Time and therefore
    # indicates that the date-time contains no information about the local
    # time zone.

    my $EmailTimeStamp = $Self->Format(
        Format => '%a, %{day} %b %Y %H:%M:%S %z',
    );

    return $EmailTimeStamp;
}

=head2 ToCTimeString()

Returns date and time as ctime string, as for example returned by Perl's C<localtime> and C<gmtime> in scalar context.

    my $CTimeString = $DateTimeObject->ToCTimeString();

Returns:

    my $String = 'Fri Feb 19 16:07:31 2016';

=cut

sub ToCTimeString {
    my ( $Self, %Param ) = @_;

    my $LocalTimeString = $Self->Format(
        Format => '%a %b %{day} %H:%M:%S %Y',
    );

    return $LocalTimeString;
}

=head2 IsVacationDay()

Checks if date/time of this object is a vacation day.

    my $IsVacationDay = $DateTimeObject->IsVacationDay(
        Calendar => 9, # optional, OTRS vacation days otherwise
    );

Returns:

    my $IsVacationDay = 'some vacation day',    # description of vacation day or 0 if no vacation day.

=cut

sub IsVacationDay {
    my ( $Self, %Param ) = @_;

    my $OriginalDateTimeValues = $Self->Get();

    # Get configured vacation days
    my $ConfigObject            = $Kernel::OM->Get('Kernel::Config');
    my $TimeVacationDays        = $ConfigObject->Get('TimeVacationDays');
    my $TimeVacationDaysOneTime = $ConfigObject->Get('TimeVacationDaysOneTime');
    if ( $Param{Calendar} ) {
        if ( $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} . "Name" ) ) {
            $TimeVacationDays        = $ConfigObject->Get( "TimeVacationDays::Calendar" . $Param{Calendar} );
            $TimeVacationDaysOneTime = $ConfigObject->Get(
                "TimeVacationDaysOneTime::Calendar" . $Param{Calendar}
            );

            # Switch to time zone of calendar
            my $TimeZone = $ConfigObject->Get( "TimeZone::Calendar" . $Param{Calendar} )
                || $Self->OTRSTimeZoneGet();

            if ( defined $TimeZone ) {
                $Self->ToTimeZone( TimeZone => $TimeZone );
            }
        }
    }

    my $DateTimeValues = $Self->Get();

    my $VacationDay        = $TimeVacationDays->{ $DateTimeValues->{Month} }->{ $DateTimeValues->{Day} };
    my $VacationDayOneTime = $TimeVacationDaysOneTime->{ $DateTimeValues->{Year} }->{ $DateTimeValues->{Month} }
        ->{ $DateTimeValues->{Day} };

    # Switch back to original time zone
    $Self->ToTimeZone( TimeZone => $OriginalDateTimeValues->{TimeZone} );

    return $VacationDay        if defined $VacationDay;
    return $VacationDayOneTime if defined $VacationDayOneTime;

    return 0;
}

=head2 LastDayOfMonthGet()

Returns the last day of the month.

    $LastDayOfMonth = $DateTimeObject->LastDayOfMonthGet();

Returns:

    my $LastDayOfMonth = {
        Day       => 31,
        DayOfWeek => 5,
        DayAbbr   => 'Fri',
    };

=cut

sub LastDayOfMonthGet {
    my ( $Self, %Param ) = @_;

    my $DateTimeValues = $Self->Get();

    my $TempCPANDateTimeObject;
    eval {
        $TempCPANDateTimeObject = DateTime->last_day_of_month(
            year  => $DateTimeValues->{Year},
            month => $DateTimeValues->{Month},
        );
    };

    return if !$TempCPANDateTimeObject;

    my $Result = {
        Day       => $TempCPANDateTimeObject->day(),
        DayOfWeek => $TempCPANDateTimeObject->day_of_week(),
        DayAbbr   => $TempCPANDateTimeObject->day_abbr(),
    };

    return $Result;
}

=head2 Clone()

Clones the DateTime object.

    my $ClonedDateTimeObject = $DateTimeObject->Clone();

=cut

sub Clone {
    my ( $Self, %Param ) = @_;

    return __PACKAGE__->new(
        _CPANDateTimeObject => $Self->{CPANDateTimeObject}->clone()
    );
}

=head2 TimeZoneList()

Returns an array ref of available time zones.

    my $TimeZones = $DateTimeObject->TimeZoneList();

You can also call this method without an object:

    my $TimeZones = Kernel::System::DateTime->TimeZoneList();

Returns:

    my $TimeZoneList = [
        # ...
        'Europe/Amsterdam',
        'Europe/Andorra',
        'Europe/Athens',
        # ...
    ];

=cut

sub TimeZoneList {
    my @TimeZones = @{ DateTime::TimeZone->all_names() };

    # add missing UTC time zone for certain DateTime versions
    my %TimeZones = map { $_ => 1 } @TimeZones;
    if ( !exists $TimeZones{UTC} ) {
        push @TimeZones, 'UTC';
    }

    return \@TimeZones;
}

=head2 TimeZoneByOffsetList()

Returns a list of time zones by offset in hours. Of course, the resulting list depends on the date/time set within this
DateTime object.

    my %TimeZoneByOffset = $DateTimeObject->TimeZoneByOffsetList();

Returns:

    my $TimeZoneByOffsetList = {
        # ...
        -9 => [ 'America/Adak', 'Pacific/Gambier', ],
        # ...
        2  => [
            # ...
            'Europe/Berlin',
            # ...
        ],
        # ...
        8.75 => [ 'Australia/Eucla', ],
        # ...
    };

=cut

sub TimeZoneByOffsetList {
    my ( $Self, %Param ) = @_;

    my $DateTimeObject = $Self->Clone();

    my $TimeZones = $Self->TimeZoneList();

    my %TimeZoneByOffset;
    for my $TimeZone ( sort @{$TimeZones} ) {
        $DateTimeObject->ToTimeZone( TimeZone => $TimeZone );
        my $TimeZoneOffset = $DateTimeObject->Format( Format => '%{offset}' ) / 60 / 60;

        if ( exists $TimeZoneByOffset{$TimeZoneOffset} ) {
            push @{ $TimeZoneByOffset{$TimeZoneOffset} }, $TimeZone;
        }
        else {
            $TimeZoneByOffset{$TimeZoneOffset} = [ $TimeZone, ];
        }
    }

    return \%TimeZoneByOffset;
}

=head2 IsTimeZoneValid()

Checks if the given time zone is valid.

    my $Valid = $DateTimeObject->IsTimeZoneValid( TimeZone => 'Europe/Berlin' );

Returns:
    $ValidID = 1;    # if given time zone is valid, 0 otherwise.

=cut

my %ValidTimeZones;    # Cache for all instances.

sub IsTimeZoneValid {
    my ( $Self, %Param ) = @_;

    for my $RequiredParam (qw( TimeZone )) {
        if ( !defined $Param{$RequiredParam} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Missing parameter $RequiredParam.",
            );
            return;
        }
    }

    # allow DateTime internal time zone in 'floating'
    return 1 if $Param{TimeZone} eq 'floating';

    if ( !%ValidTimeZones ) {
        %ValidTimeZones = map { $_ => 1 } @{ $Self->TimeZoneList() };
    }

    return $ValidTimeZones{ $Param{TimeZone} } ? 1 : 0;
}

=head2 OTRSTimeZoneGet()

Returns the time zone set for OTRS.

    my $OTRSTimeZone = $DateTimeObject->OTRSTimeZoneGet();

    # You can also call this method without an object:
    #my $OTRSTimeZone = Kernel::System::DateTime->OTRSTimeZoneGet();

Returns:

    my $OTRSTimeZone = 'Europe/Berlin';

=cut

sub OTRSTimeZoneGet {
    return $Kernel::OM->Get('Kernel::Config')->Get('OTRSTimeZone') || 'UTC';
}

=head2 UserDefaultTimeZoneGet()

Returns the time zone set as default in SysConfig UserDefaultTimeZone for newly created users or existing users without
time zone setting.

    my $UserDefaultTimeZoneGet = $DateTimeObject->UserDefaultTimeZoneGet();

You can also call this method without an object:

    my $UserDefaultTimeZoneGet = Kernel::System::DateTime->UserDefaultTimeZoneGet();

Returns:

    my $UserDefaultTimeZone = 'Europe/Berlin';

=cut

sub UserDefaultTimeZoneGet {
    return $Kernel::OM->Get('Kernel::Config')->Get('UserDefaultTimeZone') || 'UTC';
}

=head2 SystemTimeZoneGet()

Returns the time zone of the system.

    my $SystemTimeZone = $DateTimeObject->SystemTimeZoneGet();

You can also call this method without an object:

    my $SystemTimeZone = Kernel::System::DateTime->SystemTimeZoneGet();

Returns:

    my $SystemTimeZone = 'Europe/Berlin';

=cut

sub SystemTimeZoneGet {
    return DateTime::TimeZone->new( name => 'local' )->name();
}

=begin Internal:

=head2 _ToCPANDateTimeParamNames()

Maps date/time parameter names expected by the methods of this package to the ones expected by CPAN/Perl DateTime
package.

    my $DateTimeParams = $DateTimeObject->_ToCPANDateTimeParamNames(
        Year     => 2016,
        Month    => 1,
        Day      => 22,
        Hour     => 17,
        Minute   => 20,
        Second   => 2,
        TimeZone => 'Europe/Berlin',
    );

Returns:

    my $CPANDateTimeParamNames = {
        year      => 2016,
        month     => 1,
        day       => 22,
        hour      => 17,
        minute    => 20,
        second    => 2,
        time_zone => 'Europe/Berlin',
    };

=cut

sub _ToCPANDateTimeParamNames {
    my ( $Self, %Param ) = @_;

    my %ParamNameMapping = (
        Year     => 'year',
        Month    => 'month',
        Day      => 'day',
        Hour     => 'hour',
        Minute   => 'minute',
        Second   => 'second',
        TimeZone => 'time_zone',

        Years   => 'years',
        Months  => 'months',
        Weeks   => 'weeks',
        Days    => 'days',
        Hours   => 'hours',
        Minutes => 'minutes',
        Seconds => 'seconds',
    );

    my $DateTimeParams;

    PARAMNAME:
    for my $ParamName ( sort keys %ParamNameMapping ) {
        next PARAMNAME if !exists $Param{$ParamName};

        $DateTimeParams->{ $ParamNameMapping{$ParamName} } = $Param{$ParamName};
    }

    return $DateTimeParams;
}

=head2 _StringToHash()

Parses a date/time string and returns a hash ref.

    my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14 22:45:00' );

    # Sets second to 0:
    my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14 22:45' );

    # Sets hour, minute and second to 0:
    my $DateTimeHash = $DateTimeObject->_StringToHash( String => '2016-08-14' );

Please see C<L</new()>> for the list of supported string formats.

Returns:

    my $DateTimeHash = {
        Year   => 2016,
        Month  => 8,
        Day    => 14,
        Hour   => 22,
        Minute => 45,
        Second => 0,
    };

=cut

sub _StringToHash {
    my ( $Self, %Param ) = @_;

    for my $RequiredParam (qw( String )) {
        if ( !defined $Param{$RequiredParam} ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Missing parameter $RequiredParam.",
            );

            return;
        }
    }

    if ( $Param{String} =~ m{\A(\d{4})-(\d{1,2})-(\d{1,2})(\s(\d{1,2}):(\d{1,2})(:(\d{1,2}))?)?\z} ) {

        my $DateTimeHash = {
            Year   => int $1,
            Month  => int $2,
            Day    => int $3,
            Hour   => defined $5 ? int $5 : 0,
            Minute => defined $6 ? int $6 : 0,
            Second => defined $8 ? int $8 : 0,
        };

        return $DateTimeHash;
    }

    # Match the following formats:
    #   - yyyy-mm-ddThh:mm:ss+tt:zz
    #   - yyyy-mm-ddThh:mm:ss+ttzz
    #   - yyyy-mm-ddThh:mm:ss-tt:zz
    #   - yyyy-mm-ddThh:mm:ss-ttzz
    #   - yyyy-mm-ddThh:mm:ss [timezone]
    #   - yyyy-mm-ddThh:mm:ss[timezone]
    if ( $Param{String} =~ /^\d{4}-\d{1,2}-\d{1,2}T\d{1,2}:\d{1,2}:\d{1,2}(.+)$/i ) {
        my ( $Year, $Month, $Day, $Hour, $Minute, $Second, $OffsetOrTZ ) =
            ( $Param{String} =~ m/^(\d{4})-(\d{2})-(\d{2})T(\d{1,2}):(\d{1,2}):(\d{1,2})\s*(.+)$/i );

        my $DateTimeHash = {
            Year   => int $Year,
            Month  => int $Month,
            Day    => int $Day,
            Hour   => int $Hour,
            Minute => int $Minute,
            Second => int $Second,
        };

        # Check if the rest 'OffsetOrTZ' is an offset or timezone.
        #   If isn't an offset consider it a timezone
        if ( $OffsetOrTZ !~ m/(\+|\-)\d{2}:?\d{2}/i ) {

            # Make sure the time zone is valid. Otherwise, assume UTC.
            if ( !$Self->IsTimeZoneValid( TimeZone => $OffsetOrTZ ) ) {
                $OffsetOrTZ = 'UTC';
            }

            return {
                %{$DateTimeHash},
                TimeZone => $OffsetOrTZ,
            };
        }

        # It's an offset, get the time in GMT/UTC.
        $OffsetOrTZ =~ s/://i;    # Remove the ':'
        my $DT = DateTime->new(
            ( map { lcfirst $_ => $DateTimeHash->{$_} } keys %{$DateTimeHash} ),
            time_zone => $OffsetOrTZ,
        );
        $DT->set_time_zone('UTC');
        $DT->set_time_zone( $Self->OTRSTimeZoneGet() );

        return {
            ( map { ucfirst $_ => $DT->$_() } qw(year month day hour minute second) )
        };
    }

    $Kernel::OM->Get('Kernel::System::Log')->Log(
        'Priority' => 'Error',
        'Message'  => "Invalid date/time string $Param{String}.",
    );

    return;
}

=head2 _CPANDateTimeObjectCreate()

Creates a CPAN DateTime object which will be stored within this object and used for date/time calculations.

    # Create an object with current date and time
    # within time zone set in SysConfig OTRSTimeZone:
    my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate();

    # Create an object with current date and time
    # within a certain time zone:
    my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
        TimeZone => 'Europe/Berlin',
    );

    # Create an object with a specific date and time:
    my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
        Year     => 2016,
        Month    => 1,
        Day      => 22,
        Hour     => 12,                 # optional, defaults to 0
        Minute   => 35,                 # optional, defaults to 0
        Second   => 59,                 # optional, defaults to 0
        TimeZone => 'Europe/Berlin',    # optional, defaults to setting of SysConfig OTRSTimeZone
    );

    # Create an object from an epoch timestamp. These timestamps are always UTC/GMT,
    # hence time zone will automatically be set to UTC.
    #
    # If parameter Epoch is present, all other parameters except TimeZone will be ignored.
    my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
        Epoch => 1453911685,
    );

    # Create an object from a date/time string.
    #
    # If parameter String is given, Year, Month, Day, Hour, Minute and Second will be ignored. Please see C<L</new()>>
    # for the list of supported string formats.
    my $CPANDateTimeObject = $DateTimeObject->_CPANDateTimeObjectCreate(
        String   => '2016-08-14 22:45:00',
        TimeZone => 'Europe/Berlin',        # optional, defaults to setting of SysConfig OTRSTimeZone
    );

=cut

sub _CPANDateTimeObjectCreate {
    my ( $Self, %Param ) = @_;

    # Create object from string
    if ( defined $Param{String} ) {
        my $DateTimeHash = $Self->_StringToHash( String => $Param{String} );
        if ( !IsHashRefWithData($DateTimeHash) ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Invalid value for String: $Param{String}.",
            );

            return;
        }

        %Param = (
            TimeZone => $Param{TimeZone},
            %{$DateTimeHash},
        );
    }

    my $CPANDateTimeObject;
    my $TimeZone = $Param{TimeZone} || $Self->OTRSTimeZoneGet();

    if ( !$Self->IsTimeZoneValid( TimeZone => $TimeZone ) ) {
        $Kernel::OM->Get('Kernel::System::Log')->Log(
            'Priority' => 'Error',
            'Message'  => "Invalid value for TimeZone: $TimeZone.",
        );

        return;
    }

    # Create object from epoch
    if ( defined $Param{Epoch} ) {

        if ( $Param{Epoch} !~ m{\A[+-]?\d+\z}sm ) {
            $Kernel::OM->Get('Kernel::System::Log')->Log(
                'Priority' => 'Error',
                'Message'  => "Invalid value for Epoch: $Param{Epoch}.",
            );

            return;
        }

        eval {
            $CPANDateTimeObject = DateTime->from_epoch(
                epoch     => $Param{Epoch},
                time_zone => $TimeZone,
                locale    => $Self->{Locale},
            );
        };

        return $CPANDateTimeObject;
    }

    $Param{TimeZone} = $TimeZone;

    # Check if date/time params were given, excluding time zone
    my $DateTimeParamsGiven = %Param && ( !defined $Param{TimeZone} || keys %Param > 1 );

    # Create object from date/time parameters
    if ($DateTimeParamsGiven) {

        # Check existence of required params
        for my $RequiredParam (qw( Year Month Day )) {
            if ( !$Param{$RequiredParam} ) {
                $Kernel::OM->Get('Kernel::System::Log')->Log(
                    'Priority' => 'Error',
                    'Message'  => "Missing parameter $RequiredParam.",
                );
                return;
            }
        }

        # Create DateTime object
        my $DateTimeParams = $Self->_ToCPANDateTimeParamNames(%Param);

        eval {
            $CPANDateTimeObject = DateTime->new(
                %{$DateTimeParams},
                locale => $Self->{Locale},
            );
        };

        return $CPANDateTimeObject;
    }

    # Create object with current date/time.
    eval {
        $CPANDateTimeObject = DateTime->now(
            time_zone => $TimeZone,
            locale    => $Self->{Locale},
        );
    };

    return $CPANDateTimeObject;
}

=head2 _OpIsNewerThan()

Operator overloading for >

=cut

sub _OpIsNewerThan {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = $Result == 1 ? 1 : 0;

    return $Result;
}

=head2 _OpIsOlderThan()

Operator overloading for <

=cut

sub _OpIsOlderThan {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = $Result == -1 ? 1 : 0;

    return $Result;
}

=head2 _OpIsNewerThanOrEquals()

Operator overloading for >=

=cut

sub _OpIsNewerThanOrEquals {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = $Result >= 0 ? 1 : 0;

    return $Result;
}

=head2 _OpIsOlderThanOrEquals()

Operator overloading for <=

=cut

sub _OpIsOlderThanOrEquals {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = $Result <= 0 ? 1 : 0;

    return $Result;
}

=head2 _OpEquals()

Operator overloading for ==

=cut

sub _OpEquals {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = !$Result ? 1 : 0;

    return $Result;
}

=head2 _OpNotEquals()

Operator overloading for !=

=cut

sub _OpNotEquals {
    my ( $Self, $OtherDateTimeObject ) = @_;

    my $Result = $Self->Compare( DateTimeObject => $OtherDateTimeObject );
    return if !defined $Result;

    $Result = $Result != 0 ? 1 : 0;

    return $Result;
}

1;

=end Internal:

=head1 TERMS AND CONDITIONS

This software is part of the OTRS project (L<https://otrs.org/>).

This software comes with ABSOLUTELY NO WARRANTY. For details, see
the enclosed file COPYING for license information (GPL). If you
did not receive this file, see L<https://www.gnu.org/licenses/gpl-3.0.txt>.

=cut