Skip to content

Instantly share code, notes, and snippets.

@t3hk0d3
Last active April 15, 2022 18:16
Show Gist options
  • Save t3hk0d3/6186590 to your computer and use it in GitHub Desktop.
Save t3hk0d3/6186590 to your computer and use it in GitHub Desktop.
Naive implementation of Unix Timestamp to DateTime conversion
typedef struct _DateTime {
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minute;
uint8_t second;
} DateTime;
uint8_t monthDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
void datetime_update(uint32_t time, DateTime* dt) {
uint32_t days = (time / 86400);
dt->year = 1970;
dt->month = 1;
dt->day = 1;
while(1) { // rewrite this!
char leap_year = (dt->year % 4) == 0;
for(int i = 0; i < 12 ;i++) {
uint8_t days_in_month = monthDays[i];
if(i == 1 && leap_year) { // February of leap year
days_in_month++;
}
if(days < days_in_month) {
dt->day = days + 1;
days = 0;
break;
}
days -= days_in_month;
dt->month++;
}
if(days == 0) {
break;
}
dt->month = 1;
dt->year++;
}
uint32_t seconds = (time % 86400);
dt->hour = seconds / 3600;
dt->minute = (seconds % 3600) / 60;
dt->second = (seconds % 3600) % 60;
}
int main() {
init_hw();
PWR_BackupAccessCmd(ENABLE); // ugly ass construction. Time counter is write protected.
RTC_WaitForLastTask();
RTC_SetCounter(1375982740);
RTC_WaitForLastTask();
PWR_BackupAccessCmd(DISABLE);
DateTime dt;
while(1) {
uint32_t time = RTC_GetCounter(); // unix timestamp
datetime_update(time, &dt);
printf("Time is %d - %d/%02d/%02d %02d:%02d:%02d!\n", time, dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second);
delay_ms(1000);
}
}
@mdaupu
Copy link

mdaupu commented May 31, 2021

I have checked this code. Not working properly.
I gave this 1622472218 timestamp. The converted result is : 14:43:38 2-4-2026 but it should be 14:43:38 31-5-2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment