Skip to content

Instantly share code, notes, and snippets.

@lancejpollard
Forked from t3hk0d3/unixtime.c
Created April 15, 2022 18:16
Show Gist options
  • Save lancejpollard/4fae4e79b6b5175aeb6d8320a51c9c12 to your computer and use it in GitHub Desktop.
Save lancejpollard/4fae4e79b6b5175aeb6d8320a51c9c12 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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment