summaryrefslogtreecommitdiff
path: root/src/user/knob/time.c
blob: e3bbb08181a230f2700bfa51110b03484802ee89 (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
#include <pland/syscall.h>
#include <knob/time.h>
#include <stdint.h>

uint8_t days_in_months[] = {
  31,  0, 31, 30,
  31, 30, 31, 31,
  30, 31, 30, 31
};

struct time get_time() {
  struct time t;

  const uint32_t ts = _get_timestamp();
  t.timestamp = ts;

  const uint32_t time_part = ts % 86400;
  t.hour = time_part / 3600;
  t.minute = (time_part / 60) % 60;
  t.second = time_part % 60;

  uint32_t days = ts / 86400;

  uint32_t year = 2000;
  while (days >= 1461) {
    year += 4;
    days -= 1461;
  }

  days_in_months[1] = 28;
  if (days >= 1096) {
    t.year = year += 3;
    days -= 1096;
  }
  else if (days >= 731) {
    t.year = year += 2;
    days -= 731;
  }
  else if (days >= 366) {
    t.year = ++year;
    days -= 366;
  }
  else {
    t.year = year;
    days_in_months[1] = 29;
  }

  uint8_t m = 0;
  while (days >= days_in_months[m]) {
    days -= days_in_months[m];
    ++m;
  }

  t.month = m + 1;
  t.day = days + 1;
  return t;
}