summaryrefslogtreecommitdiff
path: root/euler/source/std/ctime.cpp
blob: d83817a7c30b8e48cb8396707859324e98a94ca3 (plain) (blame)
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
#include <euler/syscall.hpp>
#include <ctime>

time_t time(time_t *arg) {
  time_t t = euler::syscall::get_time();
  if (arg) *arg = t;
  return t;
}

static tm static_tm;

static int days_per_month[] = {
  31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
  31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
  31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
  31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};

tm *gmtime(const time_t *time) {

  time_t t = *time / 1024;

  static_tm.tm_isdst = 0;

  static_tm.tm_sec  = t % 60; t /= 60;
  static_tm.tm_min  = t % 60; t /= 60;
  static_tm.tm_hour = t % 24; t /= 24;
  static_tm.tm_wday = (t + 5) % 7 + 1;
  static_tm.tm_year = (t / 1461) * 4 + 100;

  int days_into_quadyear = t % 1461;

  static_tm.tm_yday = 0;
  static_tm.tm_mon = 0;
  static_tm.tm_mday = 1;

  for (int i = 0; i < 48; ++i) {
    if (days_into_quadyear >= days_per_month[i]) {
      days_into_quadyear -= days_per_month[i];
      if (static_tm.tm_mon == 11) {
        static_tm.tm_mon = 0;
        static_tm.tm_yday = 0;
      }
      else {
        ++static_tm.tm_mon;
        static_tm.tm_yday += days_per_month[i];
      }
    }
    else {
      static_tm.tm_yday += days_into_quadyear;
      static_tm.tm_mday += days_into_quadyear;
      break;
    }
  }

  return &static_tm;

}