post
poster: Thetawaves
description: Dissect unix timestamp
language: plain text
[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

#include <stdio.h>
#include <time.h>

struct m41DateBlock {
    unsigned int secs : 4;
    unsigned int tsecs : 3;
    unsigned int st : 1;
    
    unsigned int mins : 4;
    unsigned int tmins : 3;
    unsigned int placeholder1 : 1;
    
    unsigned int hours : 4;
    unsigned int thours : 2;
    unsigned int CB0 : 1;
    unsigned int CB1 : 1;
    
    unsigned int DayOfWeek : 3;
    unsigned int placeholder2 : 5;
    
    unsigned int DayOfMonth : 4;
    unsigned int tDayOfMonth : 2;
    unsigned int placeholder3 : 2;
    
    unsigned int Month : 4;
    unsigned int tMonth : 1;
    unsigned int placeholder4 : 3;
    
    unsigned int Year : 4;
    unsigned int tYear : 4;
};

int leapYearsBefore (int year)
{
    year--;
    return (year/4) - (year/100) + (year/400);
}
int isLeapYear(int year)
{
    if (year % 400 == 0)
        return 1;
    else if (year % 100 == 0)
        return 0;
    else if (year % 4 == 0)
        return 1;
    else    return 0;
}
int set_time(time_t timestamp)
{
    struct m41DateBlock dateblock;
    
    unsigned char month_lens[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
    unsigned char month_index = 0;
    
    unsigned int total_days = timestamp/86400;
    unsigned int rem_secs = timestamp % 86400;
    
    unsigned int guess_leap_years = leapYearsBefore(1970 + (total_days/365)) - leapYearsBefore(1970);
    unsigned int total_years = 1970 + ((total_days - guess_leap_years)/365);
    unsigned int rem_days = ((total_days - guess_leap_years) % 365);
    printf("year: %i\n", total_years);
    
    dateblock.tYear = total_years / 10;
    dateblock.Year = total_years % 10;
    
    if (isLeapYear(total_years))
        month_lens[1] = 29;
        
    for (; rem_days > month_lens[month_index] && month_index < 12; month_index++)
        rem_days -= month_lens[month_index];
        
    dateblock.tMonth = (month_index + 1) / 10;
    dateblock.Month = (month_index + 1) % 10;
    
    dateblock.tDayOfMonth = rem_days / 10;
    dateblock.DayOfMonth = rem_days % 10;
    
    dateblock.thours = (rem_secs / 3600) / 10;
    dateblock.hours = (rem_secs / 3600) % 10;
    
    rem_secs = (rem_secs % 3600);
    
    dateblock.tmins = (rem_secs / 60) / 10;
    dateblock.mins = (rem_secs / 60) % 10;
    
    rem_secs = (rem_secs % 60);

    dateblock.tsecs = rem_secs / 10;
    dateblock.secs = rem_secs % 10;
}

int main() {
    time_t tstamp;
    
    tstamp = time(NULL);
    set_time(tstamp);
}