Custom date type.

My program is using dates which exceed the bounds of 32bit time_t, in addition manipulating days via time_t is a pain. The idea is simple enough, convert a date string to a 32bit unsigned integer format where 0 represents 01/01/1800, 1 represents 02/01/1800, 2 represents 03/01/1800 (you get the picture) etc and back again to a string. I'm quite close yet I haven't been able to completely achieve this. If anyone can point out where I am going wrong that would be of great help.

PS, I'm British so the date format is as follows "dd mm yyyy".

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
const u_int32_t daysnorm[] = {0,31,59,90,120,151,181,212,243,273,304,334,365};
const u_int32_t daysleap[] = {0,31,60,91,121,152,182,213,244,274,305,335,366};

inline bool isleap(u_int32_t year) {
    return ((year % 4 == 0 && year % 100 != 0) || ( year % 400 == 0));
}

inline u_int32_t totaldays(u_int32_t year) {
    return (isleap(year) ? 366 : 365);
}

inline u_int32_t datevalue(std::string datestring) {
    u_int32_t datevalue = 0;
    u_int32_t year = 0, month = 0, day = 0;
    
    std::istringstream(datestring) >> day >> month >> year;
    
    datevalue += day - 1;
    datevalue += (isleap(year) ? daysleap[month-1] : daysnorm[month-1]);
    
    for(u_int32_t i = 1800; i < year; i++) {
        datevalue += totaldays(year);
    }
    
    return datevalue;
}

inline std::string datestring(u_int32_t datevalue) {
    u_int32_t year = 1800, month = 1, day = 1;
    
    for(; datevalue > totaldays(year); datevalue -= totaldays(year)) {
        year++;
    }
    
    for(u_int32_t i = 0; i < sizeof(daysleap); i++) {
        if((isleap(year) ? daysleap[i] : daysnorm[i]) > datevalue) {
            datevalue -= (isleap(year) ? daysleap[i-1] : daysnorm[i-1]);
            month = i;
            i = sizeof(daysleap);
        }
    }
    
    day = datevalue + 1;
    
    std::stringstream ss;
    ss << day << " " << month << " " << year;
    
    return ss.str();
}
This is the julian day approach:

http://en.wikipedia.org/wiki/Julian_day

There you find the formulas required for the convertion

You may also take a look at this

http://www.cplusplus.com/reference/ctime/strftime/

it displays the calculated date/time human readable
That was of little to no help. Fixed it regardless.
Topic archived. No new replies allowed.