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
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger <sm@opengate.at>                 |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/times.h"
#include "gate/debugging.h"
#include "gate/results.h"
#include "gate/strings.h"

#if defined(GATE_SYS_WIN16)
#	define GATE_CORE_TIMES_C_IMPL	1
#elif defined(GATE_SYS_WIN)
#	define GATE_CORE_TIMES_WINAPI_IMPL	1
#elif defined(GATE_SYS_BEOS)
#	define GATE_CORE_TIMES_BEOS_IMPL 1
#elif defined(GATE_SYS_POSIX)
#	define GATE_CORE_TIMES_POSIX_IMPL	1
#elif defined(GATE_SYS_DOS)
#	define GATE_CORE_TIMES_DOS_IMPL		1
#elif defined(GATE_SYS_EFI)
#	define GATE_CORE_TIMES_EFI_IMPL		1
#elif defined(GATE_SYS_WASM)
#	define GATE_CORE_TIMES_WASM_IMPL	1
#else
#	define GATE_CORE_TIMES_C_IMPL		1
#endif


static gate_int64_t const gate_time_microseconds_per_day = 86400000000;

static gate_int64_t const gate_time_unix_start = 11644473600000000;


static gate_bool_t gate_time_is_leap_year(gate_uint16_t year)
{
    if (0 == (year % 400)) return true;
    if (0 == (year % 100)) return false;
    if (0 == (year % 4)) return true;
    return false;
}
static gate_uint16_t gate_time_get_days_of_year(gate_uint16_t year)
{
    return gate_time_is_leap_year(year) ? 366 : 365;
}
static gate_uint8_t gate_time_get_days_of_month(gate_uint16_t year, gate_uint8_t month)
{
    switch (month)
    {
    case GATE_DATE_JAN:
    case GATE_DATE_MAR:
    case GATE_DATE_MAY:
    case GATE_DATE_JUL:
    case GATE_DATE_AUG:
    case GATE_DATE_OCT:
    case GATE_DATE_DEC:
        return 31;
    case GATE_DATE_APR:
    case GATE_DATE_JUN:
    case GATE_DATE_SEP:
    case GATE_DATE_NOV:
        return 30;
    case GATE_DATE_FEB:
        return gate_time_is_leap_year(year) ? 29 : 28;
    default:
        return 0;
    }
}


gate_result_t gate_time_to_datetime(gate_time_t const* source, gate_datetime_t* dest)
{
    gate_int64_t timestamp = source->timestamp + ((gate_int64_t)source->bias) * 60000000;
    gate_int64_t timecounter = 0;
    gate_uint16_t year = 1601;
    gate_uint8_t month = 1;
    gate_uint8_t day = 1;
    gate_uint8_t hour = 0;
    gate_uint8_t minute = 0;
    gate_uint8_t second = 0;
    gate_uint32_t microsecond = 0;
    gate_int64_t tmp;

    if (timestamp >= gate_time_unix_start)
    {
        timecounter = gate_time_unix_start;
        year = 1970;
    }

    for (;;)
    {
        /* lenght of current year in microseconds */
        tmp = gate_time_microseconds_per_day * (gate_int64_t)gate_time_get_days_of_year(year);
        if (timecounter + tmp <= timestamp)
        {
            ++year;
            timecounter += tmp;
        }
        else
        {
            break;
        }
    }
    /* year is fixed */
    for (month = 1; ;)
    {
        tmp = gate_time_microseconds_per_day * (gate_int64_t)gate_time_get_days_of_month(year, month);
        if (timecounter + tmp <= timestamp)
        {
            ++month;
            timecounter += tmp;
        }
        else
        {
            break;
        }
    }
    for (day = 1; day < 32;)
    {
        if (timecounter + gate_time_microseconds_per_day <= timestamp)
        {
            ++day;
            timecounter += gate_time_microseconds_per_day;
        }
        else
        {
            break;
        }
    }

    timecounter = timestamp - timecounter;

    hour = (gate_uint8_t)(timecounter / 3600000000);
    tmp = timecounter % 3600000000;
    minute = (gate_uint8_t)(tmp / 60000000);
    tmp = tmp % 60000000;
    second = (gate_uint8_t)(tmp / 1000000);
    microsecond = (gate_uint32_t)(tmp % 1000000);

    dest->date.year = year;
    dest->date.month = month;
    dest->date.day = day;
    dest->time.hour = hour;
    dest->time.minute = minute;
    dest->time.second = second;
    dest->time.microsecond = microsecond;

    return GATE_RESULT_OK;
}


static gate_uint64_t const SECONDS_PER_DAY = 86400;
static gate_uint64_t const SECONDS_PER_HOUR = 3600;
static gate_uint64_t const SECONDS_PER_MINUTE = 60;


gate_result_t gate_date_to_time(gate_datetime_t const* source, gate_time_t* dest)
{
    gate_result_t ret;
    gate_uint16_t year;
    gate_uint8_t month;
    gate_int64_t daycounter;
    gate_uint64_t seconds;

    do
    {
        if ((source->date.year < 1601) || (source->date.month < 1) || (source->date.month > 12) || (source->date.day < 1) || (source->date.day > 31)
            )
        {
            ret = GATE_RESULT_INVALIDARG;
            break;
        }
        daycounter = 0;
        for (year = 1601; year < source->date.year; ++year)
        {
            daycounter += gate_time_get_days_of_year(year);
        }
        for (month = 1; month < source->date.month; ++month)
        {
            daycounter += gate_time_get_days_of_month(source->date.year, month);
        }
        daycounter += (source->date.day - 1);

        seconds = (gate_uint64_t)daycounter * SECONDS_PER_DAY
            + (gate_uint64_t)source->time.hour * SECONDS_PER_HOUR
            + (gate_uint64_t)source->time.minute * SECONDS_PER_MINUTE
            + (gate_uint64_t)source->time.second;

        dest->bias = 0;
        dest->timestamp
            = seconds * ((gate_uint64_t)1000000)
            + source->time.microsecond;
        ;
        ret = GATE_RESULT_OK;
    } while (0);

    return ret;
}

typedef struct month_mapping_class
{
    unsigned month;
    unsigned name_len;
    char const* name;
} month_mapping_t;

static month_mapping_t short_months[] = {
    { GATE_DATE_JAN, 3, "Jan" },
    { GATE_DATE_FEB, 3, "Feb" },
    { GATE_DATE_MAR, 3, "Mar" },
    { GATE_DATE_APR, 3, "Apr" },
    { GATE_DATE_MAY, 3, "May" },
    { GATE_DATE_JUN, 3, "Jun" },
    { GATE_DATE_JUL, 3, "Jul" },
    { GATE_DATE_AUG, 3, "Aug" },
    { GATE_DATE_SEP, 3, "Sep" },
    { GATE_DATE_OCT, 3, "Oct" },
    { GATE_DATE_NOV, 3, "Nov" },
    { GATE_DATE_DEC, 3, "Dec" }
};

static month_mapping_t long_months[] = {
    { GATE_DATE_JAN, 7, "January" },
    { GATE_DATE_FEB, 8, "February" },
    { GATE_DATE_MAR, 5, "March" },
    { GATE_DATE_APR, 5, "April" },
    { GATE_DATE_MAY, 3, "May" },
    { GATE_DATE_JUN, 4, "June" },
    { GATE_DATE_JUL, 4, "July" },
    { GATE_DATE_AUG, 6, "August" },
    { GATE_DATE_SEP, 9, "September" },
    { GATE_DATE_OCT, 7, "October" },
    { GATE_DATE_NOV, 8, "November" },
    { GATE_DATE_DEC, 8, "December" }
};

gate_size_t gate_time_print_month(char* dest, gate_size_t destlength, gate_uint8_t month, gate_bool_t shortname)
{
    if (shortname)
    {
        if ((month >= 1) && (month <= 12))
        {
            return gate_str_print_text(dest, destlength, short_months[month - 1].name, short_months[month - 1].name_len);
        }
    }
    else
    {
        if ((month >= 1) && (month <= 12))
        {
            return gate_str_print_text(dest, destlength, long_months[month - 1].name, long_months[month - 1].name_len);
        }
    }
    return 0;
}

gate_size_t	gate_date_parse_month(char const* source, gate_size_t sourcelen, gate_uint8_t* mon)
{
    unsigned n;
    for (n = 0; n < 12; ++n)
    {
        if ((0 == gate_str_compare(short_months[n].name, short_months[n].name_len, source, sourcelen))
            || (0 == gate_str_compare(long_months[n].name, long_months[n].name_len, source, sourcelen))
            )
        {
            *mon = (gate_uint8_t)(n + 1);
            return sourcelen;
        }
    }
    return 0;
}


gate_size_t gate_time_print_bias(char* dest, gate_size_t destlength, gate_int16_t bias)
{
    gate_size_t ret = 0;
    gate_bool_t neg;
    gate_uint8_t hour;
    gate_uint8_t minute;
    /*+hh:mm*/
    if (destlength < 6)
    {
        ret = 0;
    }
    else
    {
        if (bias < 0)
        {
            neg = true;
            bias = -bias;
        }
        else
        {
            neg = false;
        }

        hour = (gate_uint8_t)(bias / 60);
        minute = (gate_uint8_t)(bias % 60);

        dest[0] = neg ? '-' : '+';
        gate_str_print_uint(&dest[1], 2, hour, 2);
        dest[3] = ':';
        gate_str_print_uint(&dest[4], 2, minute, 2);

        ret = 6;
    }

    return ret;
}

static gate_string8_t const gate_time_token_year4 = { "{YYYY}", 6, NULL };
static gate_string8_t const gate_time_token_year2 = { "{YY}" , 4 };
static gate_string8_t const gate_time_token_month2 = { "{MM}" , 4 };
static gate_string8_t const gate_time_token_month1 = { "{M}" , 3 };
static gate_string8_t const gate_time_token_monthname = { "{MNA}" , 5 };
static gate_string8_t const gate_time_token_monthnameshort = { "{MN}" , 4 };
static gate_string8_t const gate_time_token_day2 = { "{DD}" , 4 };
static gate_string8_t const gate_time_token_day1 = { "{D}" , 3 };
static gate_string8_t const gate_time_token_hour2 = { "{hh}" , 4 };
static gate_string8_t const gate_time_token_hour1 = { "{h}" , 3 };
static gate_string8_t const gate_time_token_hour2_12 = { "{kk}" , 4 };
static gate_string8_t const gate_time_token_hour1_12 = { "{k}" , 3 };
static gate_string8_t const gate_time_token_ampm = { "{ampm}" , 6 };
static gate_string8_t const gate_time_token_minute2 = { "{mm}" , 4 };
static gate_string8_t const gate_time_token_minute1 = { "{m}" , 3 };
static gate_string8_t const gate_time_token_second2 = { "{ss}" , 4 };
static gate_string8_t const gate_time_token_second1 = { "{s}" , 3 };
static gate_string8_t const gate_time_token_fraction1 = { "{S}" , 3 };
static gate_string8_t const gate_time_token_fraction2 = { "{SS}" , 4 };
static gate_string8_t const gate_time_token_fraction3 = { "{SSS}" , 5 };
static gate_string8_t const gate_time_token_fraction4 = { "{SSSS}" , 6 };
static gate_string8_t const gate_time_token_fraction5 = { "{SSSSS}" , 7 };
static gate_string8_t const gate_time_token_fraction6 = { "{SSSSSS}" , 8 };
static gate_string8_t const gate_time_token_bias = { "{bias}" , 6 };

gate_result_t gate_date_to_string(gate_datetime_t const* date, gate_int16_t bias_minutes, char const* format, char* dest, gate_size_t* destsize)
{
    static char const* const formatISO1801 = "{YYYY}-{MM}-{DD}T{hh}:{mm}:{ss}.{SSS}{bias}";
    gate_string_t token;
    gate_size_t destlength = destsize ? *destsize : 0;
    gate_size_t tmptokenlen = 0;
    gate_size_t used = 0;
    gate_size_t lenprinted = 0;

    if (format == NULL)
    {
        format = formatISO1801;
    }

    gate_string_create_static(&token, format);

    while (token.length != 0)
    {
        if (gate_string_starts_with(&token, &gate_time_token_year4))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->date.year, 4);
            tmptokenlen = gate_time_token_year4.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_year2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->date.year, 2);
            tmptokenlen = gate_time_token_year2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_month2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->date.month, 2);
            tmptokenlen = gate_time_token_month2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_month1))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, date->date.month);
            tmptokenlen = gate_time_token_month1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_monthname))
        {
            lenprinted = gate_time_print_month(dest, destlength, date->date.month, false);
            tmptokenlen = gate_time_token_monthname.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_monthnameshort))
        {
            lenprinted = gate_time_print_month(dest, destlength, date->date.month, true);
            tmptokenlen = gate_time_token_monthnameshort.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_day2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->date.day, 2);
            tmptokenlen = gate_time_token_day2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_day1))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, date->date.day);
            tmptokenlen = gate_time_token_day1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_hour2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.hour, 2);
            tmptokenlen = gate_time_token_hour2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_hour1))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, date->time.hour);
            tmptokenlen = gate_time_token_hour1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_hour2_12))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.hour > 12 ? date->time.hour - 12 : date->time.hour, 2);
            tmptokenlen = gate_time_token_hour2_12.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_hour1_12))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, (gate_uint16_t)((date->time.hour > 12) ? (date->time.hour - 12) : date->time.hour));
            tmptokenlen = gate_time_token_hour1_12.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_ampm))
        {
            if (date->time.hour > 12)
            {
                lenprinted = gate_str_print_text(dest, destlength, "pm", 2);
            }
            else
            {
                lenprinted = gate_str_print_text(dest, destlength, "am", 2);
            }
            tmptokenlen = gate_time_token_ampm.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_minute2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.minute, 2);
            tmptokenlen = gate_time_token_minute2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_minute1))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, date->time.minute);
            tmptokenlen = gate_time_token_minute1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_second2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.second, 2);
            tmptokenlen = gate_time_token_second2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_second1))
        {
            lenprinted = gate_str_print_uint16(dest, destlength, date->time.second);
            tmptokenlen = gate_time_token_second1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction1))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond / 100000, 1);
            tmptokenlen = gate_time_token_fraction1.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction2))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond / 10000, 2);
            tmptokenlen = gate_time_token_fraction2.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction3))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond / 1000, 3);
            tmptokenlen = gate_time_token_fraction3.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction4))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond / 100, 4);
            tmptokenlen = gate_time_token_fraction4.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction5))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond / 10, 5);
            tmptokenlen = gate_time_token_fraction5.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_fraction6))
        {
            lenprinted = gate_str_print_uint(dest, destlength, date->time.microsecond, 6);
            tmptokenlen = gate_time_token_fraction6.length;
        }
        else if (gate_string_starts_with(&token, &gate_time_token_bias))
        {
            lenprinted = gate_time_print_bias(dest, destlength, bias_minutes);
            tmptokenlen = gate_time_token_bias.length;
        }
        else
        {
            if (destlength != 0)
            {
                *dest = *token.str;
                lenprinted = 1;
                tmptokenlen = 1;
            }
            else
            {
                lenprinted = 0;
            }
        }

        if (lenprinted == 0)
        {
            break;
        }
        token.str += tmptokenlen;
        token.length -= tmptokenlen;
        used += lenprinted;
        dest += lenprinted;
        destlength -= lenprinted;
    };
    if (destlength != 0)
    {
        *dest = '\0';
    }

    if (destsize)
    {
        *destsize = used;
    }
    return GATE_RESULT_OK;

}

gate_result_t gate_time_to_string(gate_time_t const* source, char const* format, char* dest, gate_size_t* destsize)
{
    gate_result_t result;
    gate_datetime_t date;
    result = gate_time_to_datetime(source, &date);
    if (GATE_SUCCEEDED(result))
    {
        result = gate_date_to_string(&date, source->bias, format, dest, destsize);
    }
    return result;
}

static gate_bool_t get_time_u8(char const* text, gate_size_t len, gate_uint8_t* ptr)
{
    gate_uint64_t tmp;
    if (len == gate_str_parse_uint64(text, len, &tmp))
    {
        *ptr = (gate_uint8_t)tmp;
        return true;
    }
    else
    {
        return false;
    }
}
static gate_bool_t get_time_u16(char const* text, gate_size_t len, gate_uint16_t* ptr)
{
    gate_uint64_t tmp;
    if (len == gate_str_parse_uint64(text, len, &tmp))
    {
        *ptr = (gate_uint16_t)tmp;
        return true;
    }
    else
    {
        return false;
    }
}

gate_size_t gate_date_parse_string(char const* source, gate_size_t sourcelen, gate_datetime_t* dest, gate_int16_t* bias)
{
    gate_size_t ret = 0;
    gate_uint8_t tmp;
    char const* ptr;
    gate_size_t ptrlen;
    gate_uint32_t microsec_factor = 100000;
    gate_int16_t local_bias = 0;

    /*YYYY-MM-DDThh:mm:ss.iii+HH:MM */
    do
    {
        gate_mem_clear(dest, sizeof(gate_datetime_t));
        if (sourcelen < 10) break;
        if ((source[4] != '-') || (source[7] != '-')) break;

        if (!get_time_u16(&source[0], 4, &dest->date.year)) break;
        if (!get_time_u8(&source[5], 2, &dest->date.month)) break;
        if (!get_time_u8(&source[8], 2, &dest->date.day)) break;
        ret = 10;<--- Variable 'ret' is reassigned a value before the old one has been used.

        if (sourcelen < 13) break;
        if ((source[10] != ' ') && (source[10] != 'T')) break;
        if (!get_time_u8(&source[11], 2, &dest->time.hour)) break;
        ret = 13;<--- Variable 'ret' is reassigned a value before the old one has been used.<--- Variable 'ret' is reassigned a value before the old one has been used.

        if (sourcelen < 16) break;
        if (source[13] != ':') break;
        if (!get_time_u8(&source[14], 2, &dest->time.minute)) break;
        ret = 16;<--- Variable 'ret' is reassigned a value before the old one has been used.<--- Variable 'ret' is reassigned a value before the old one has been used.

        if (sourcelen < 19) break;
        if (source[16] != ':') break;
        if (!get_time_u8(&source[17], 2, &dest->time.second)) break;
        ret = 19;<--- Variable 'ret' is reassigned a value before the old one has been used.

        if (sourcelen > 19)
        {
            ptr = &source[19];
            ptrlen = sourcelen - 19;

            if (*ptr == '.')
            {
                ++ret;
                --ptrlen;
                while ((ptrlen != 0) && (microsec_factor > 0))
                {
                    if (!gate_char_is_digit(*ptr)) break;
                    dest->time.microsecond += (gate_uint32_t)(*ptr - '0') * microsec_factor;
                    microsec_factor /= 10;
                    ++ptr;
                    --ptrlen;
                    ++ret;
                }
            }
            if (ptrlen >= 3)
            {
                if ((ptr[0] == '+') || (ptr[0] == '-'))
                {
                    if (!get_time_u8(&ptr[1], 2, &tmp)) break;
                    local_bias = (gate_int16_t)tmp * 60;
                    ret += 3;

                    if ((ptrlen >= 6) && (ptr[3] == ':'))
                    {
                        if (get_time_u8(&ptr[4], 2, &tmp))
                        {
                            local_bias += (gate_int16_t)tmp;
                            ret += 3;
                        }
                    }
                    if (ptr[0] == '-')
                    {
                        local_bias *= -1;
                    }
                }
            }
        }

    } while (0);

    if (bias)
    {
        *bias = local_bias;
    }

    return ret;
}

gate_day_id_t gate_date_to_day_id(gate_date_t const* date)
{
    gate_datetime_t dt;
    gate_time_t tm;
    gate_result_t res;

    dt.date = *date;
    gate_mem_clear(&dt.time, sizeof(dt.time));
    res = gate_date_to_time(&dt, &tm);
    if (GATE_SUCCEEDED(res))
    {
        return gate_time_to_day_id(tm.timestamp);
    }
    else
    {
        return 0;
    }
}

gate_result_t gate_date_from_day_id(gate_day_id_t day_id, gate_date_t* date)
{
    gate_result_t ret;
    gate_time_t tm = GATE_INIT_EMPTY;
    gate_datetime_t dt = GATE_INIT_EMPTY;
    do
    {
        ret = gate_time_from_day_id(day_id, &tm.timestamp);
        GATE_BREAK_IF_FAILED(ret);
        ret = gate_time_to_datetime(&tm, &dt);
        GATE_BREAK_IF_FAILED(ret);
        *date = dt.date;
    } while (0);
    return ret;
}

gate_uint8_t gate_date_day_of_week(gate_day_id_t day_id)
{
    return (gate_uint8_t)((gate_uint32_t)day_id % 7);
}

gate_uint16_t gate_date_day_of_year(gate_date_t const* date)
{
    gate_uint16_t ret = 0;
    gate_uint8_t month;

    for (month = 1; month != date->month; ++month)
    {
        ret += gate_time_get_days_of_month(date->year, month);
    }
    ret += date->day;

    return ret;
}

gate_uint8_t gate_date_week_of_year(gate_date_t const* date, gate_bool_t monday_starts_week)
{
    gate_uint8_t ret = 0;
    gate_uint16_t day_of_year = gate_date_day_of_year(date);
    gate_uint8_t day_of_week = gate_date_day_of_week(gate_date_to_day_id(date));

    if (monday_starts_week)
    {
        ret = (gate_uint8_t)(((day_of_year + 5 - ((day_of_week + 1) % 7)) / 7) + 1);
    }
    else
    {
        ret = (gate_uint8_t)(((day_of_year + 5 - day_of_week + 1) / 7) + 1);
    }
    return ret;
}

gate_day_id_t gate_time_to_day_id(gate_timestamp_t timestamp)
{
    gate_int32_t days_since_1601 = (gate_int32_t)(timestamp / gate_time_microseconds_per_day);
    return days_since_1601 + 1;
}

gate_result_t gate_time_from_day_id(gate_day_id_t day_id, gate_timestamp_t* dest)
{
    if (day_id <= 0)
    {
        return GATE_RESULT_INVALIDARG;
    }
    else
    {
        *dest = (((gate_timestamp_t)(day_id)-1) * gate_time_microseconds_per_day);
        return GATE_RESULT_OK;
    }
}



gate_result_t gate_time_parse_string(char const* source, gate_size_t sourcelen, gate_time_t* dest)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    gate_datetime_t date = GATE_INIT_EMPTY;
    gate_int16_t bias = 0;
    gate_size_t bytes_parsed = gate_date_parse_string(source, sourcelen, &date, &bias);
    if (bytes_parsed != 0)
    {
        gate_mem_clear(dest, sizeof(gate_time_t));
        ret = gate_date_to_time(&date, dest);
        dest->bias = bias;
    }
    return ret;
}

gate_result_t gate_time_from_timestamp(gate_timestamp_t source, gate_time_t* dest)
{
    gate_result_t ret;
    /* should return local BIAS of timestamp, but at the moment
       we only return the current bias */
    ret = gate_time_now(dest);
    dest->timestamp = source;

    return ret;
}

/* 0x00295E9648864000 or ‭11644473600000000‬ == 1970-01-01T00:00 */
static gate_int64_t const unix_epoche = 11644473600000000;

gate_result_t gate_time_from_unix(gate_int64_t sourceunixseconds, gate_timestamp_t* dest)
{
    gate_result_t ret = GATE_RESULT_OK;
    *dest = unix_epoche + (sourceunixseconds * 1000000);
    return ret;
}
gate_result_t gate_time_to_unix(gate_timestamp_t sourcetime, gate_int64_t* destunixseconds)
{
    gate_result_t ret = GATE_RESULT_OK;
    *destunixseconds = (sourcetime - unix_epoche) / 1000000;
    return ret;
}


#if defined(GATE_CORE_TIMES_WINAPI_IMPL)

#include "gate/platforms.h"
#include "gate/platform/windows/wince_patches.h"

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    ULONGLONG tc = gate_win32_get_tick_count();
    *now = (gate_int64_t)tc * 1000;
    return GATE_RESULT_OK;
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}

gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    gate_result_t ret = GATE_RESULT_FAILED;
    FILETIME sft;
    FILETIME lft;
    gate_uint64_t global_time;
    gate_uint64_t local_time;
    GetSystemTimeAsFileTime(&sft);
    FileTimeToLocalFileTime(&sft, &lft);
    global_time = ((((gate_uint64_t)sft.dwHighDateTime) << 32) | (gate_uint64_t)sft.dwLowDateTime) / 10;
    local_time = ((((gate_uint64_t)lft.dwHighDateTime) << 32) | (gate_uint64_t)lft.dwLowDateTime) / 10;

    now->timestamp = global_time;
    now->bias = (gate_int32_t)(((gate_int64_t)local_time - (gate_int64_t)global_time) / 60000000);
    ret = GATE_RESULT_OK;
    return ret;
}

#endif /* GATE_CORE_TIMES_WINAPI_IMPL */



#if defined(GATE_CORE_TIMES_POSIX_IMPL)

#include <time.h>
#include <sys/time.h>

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    struct timespec ts;
    if (0 == clock_gettime(CLOCK_MONOTONIC, &ts))
    {
        *now = (gate_int64_t)ts.tv_sec * 1000000LL + (gate_int64_t)ts.tv_nsec / 1000;
        return GATE_RESULT_OK;
    }
    else
    {
        return GATE_RESULT_FAILED;
    }
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}
gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    struct timeval tv;
    time_t rawtime;
    time_t loctime;
    time_t tret;
    struct tm globtm;
    struct tm loctm;
    struct tm* tmp;
    int result = gettimeofday(&tv, NULL);
    if (result == -1)
    {
        return GATE_RESULT_FAILED;
    }
    now->timestamp = gate_time_unix_start + ((gate_int64_t)tv.tv_sec) * 1000000LL + tv.tv_usec;
    now->bias = 0;
    tret = time(&rawtime);
    if (tret != (time_t)-1)
    {
        tmp = gmtime_r(&rawtime, &globtm);
        if (tmp != NULL)
        {
            if (localtime_r(&rawtime, &loctm))
            {
                globtm.tm_isdst = loctm.tm_isdst;
            }
            loctime = mktime(&globtm);
            if (loctime != (time_t)-1)
            {
                now->bias = (rawtime - loctime) / 60;
            }
        }
    }

    return GATE_RESULT_OK;
}

#endif /* GATE_CORE_TIMES_POSIX_IMPL */



#if defined(GATE_CORE_TIMES_BEOS_IMPL)

#include <kernel/OS.h>

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    bigtime_t tc = system_time();
    *now = (gate_timecounter_t)tc;
    return GATE_RESULT_OK;
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}
gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    gate_result_t result;
    gate_timestamp_t ts;
    bigtime_t unix_time_us = real_time_clock_usecs();
    gate_int64_t unix_time_sec = (gate_int64_t)unix_time_us / 1000000;
    gate_int64_t usec = unix_time_us % 1000000;

    result = gate_time_from_unix(unix_time_sec, &ts);
    if (GATE_SUCCEEDED(result))
    {
        now->bias = 0;
        now->timestamp += ts + usec;
    }
    return result;
}

#endif /* GATE_CORE_TIMES_BEOS_IMPL */



#if defined(GATE_CORE_TIMES_DOS_IMPL)

#include <dos.h>
#include <time.h>
#include "gate/platforms.h"

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    gate_uint32_t clock_ms;
    if (now)
    {
        clock_ms = gate_dos_clock_get();
        *now = (gate_int64_t)clock_ms * 1000;
    }
    return GATE_RESULT_OK;
}

gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}

gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}


gate_result_t gate_time_now(gate_time_t* now)
{
    gate_datetime_t dt;
    struct dosdate_t dosdate;
    struct dostime_t dostime;

    _dos_getdate(&dosdate);
    _dos_gettime(&dostime);

    dt.date.year = dosdate.year + 1980;
    dt.date.month = dosdate.month;
    dt.date.day = dosdate.day;
    dt.time.hour = dostime.hour;
    dt.time.minute = dostime.minute;
    dt.time.second = dostime.second;
    dt.time.microsecond = (gate_uint32_t)dostime.hsecond * 10000;

    return gate_date_to_time(&dt, now);
}

#endif /* GATE_CORE_TIMES_DOS_IMPL */


#if defined(GATE_CORE_TIMES_EFI_IMPL)

#include "gate/platform/efi/efi_gate.h"

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    gate_time_t tm_now;
    gate_result_t ret = gate_time_now(&tm_now);
    if (GATE_SUCCEEDED(ret))
    {
        if (now)
        {
            *now = tm_now.timestamp;
        }
    }
    return ret;
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}

gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    gate_int64_t ms_since_epoche = 0;
    gate_timestamp_t ts = 0;
    gate_result_t ret = gate_platform_efi_time_now(&ms_since_epoche);
    if (GATE_SUCCEEDED(ret))
    {
        ret = gate_time_from_unix(ms_since_epoche / 1000, &ts);
        if (GATE_SUCCEEDED(ret))
        {
            if (now)
            {
                now->timestamp += (ms_since_epoche % 1000) * 1000;<--- Variable 'now->timestamp' is reassigned a value before the old one has been used.
                now->timestamp = ts;<--- Variable 'now->timestamp' is reassigned a value before the old one has been used.
                now->bias = 0;
            }
        }
    }
    return ret;
}

#endif /* GATE_CORE_TIMES_EFI_IMPL */



#if defined(GATE_CORE_TIMES_WASM_IMPL)

#include "gate/platform/wasm/wasm_gate.h"
#include <emscripten/html5.h>

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    double us = (emscripten_performance_now() * 1000.0);
    if (now)
    {
        *now = (gate_timecounter_t)(gate_int64_t)us;
    }
    return GATE_RESULT_OK;
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}

gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    double unix_us = emscripten_date_now() * 1000.0;
    gate_timestamp_t ts = (gate_timestamp_t)(gate_time_unix_start + (gate_int64_t)unix_us);
    if (now)
    {
        now->timestamp = ts;
        now->bias = 0;
    }
    return GATE_RESULT_OK;
}

#endif /* GATE_CORE_TIMES_WASM_IMPL */



#if defined(GATE_CORE_TIMES_C_IMPL)

#include <time.h>

gate_result_t gate_timecounter_now(gate_timecounter_t* now)
{
    double micro_seconds = ((double)clock() / (double)CLOCKS_PER_SEC) * 1000000.0;

    gate_int64_t us = (gate_int64_t)micro_seconds;
    if (now)
    {
        *now = (gate_timecounter_t)us;
    }
    return GATE_RESULT_OK;
}
gate_int64_t gate_timecounter_diff(gate_timecounter_t tc1, gate_timecounter_t tc2)
{
    return (tc1 - tc2);
}

gate_timecounter_t gate_timecounter_add(gate_timecounter_t tc, gate_int64_t microseconds)
{
    return tc + microseconds;
}

gate_result_t gate_time_now(gate_time_t* now)
{
    gate_int64_t t = (gate_int64_t)time(NULL) * 1000000LL;

    gate_timestamp_t ts = (gate_timestamp_t)(gate_time_unix_start + t);
    if (now)
    {
        now->timestamp = ts;
        now->bias = 0;
    }
    return GATE_RESULT_OK;
}

#endif /* GATE_CORE_TIMES_C_IMPL */