From 21d9060e9f50479af5205468dd859a3449cd2b35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ng=C3=B4=20Ng=E1=BB=8Dc=20=C4=90=E1=BB=A9c=20Huy?= Date: Wed, 23 Jun 2021 11:17:00 +0700 Subject: [PATCH] Add date functionalities --- date.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ date.h | 8 ++++++++ wochabit.c | 9 +++++++++ 3 files changed, 65 insertions(+) create mode 100644 date.c create mode 100644 date.h diff --git a/date.c b/date.c new file mode 100644 index 0000000..c514686 --- /dev/null +++ b/date.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include + +#include "date.h" +#include "config.h" + +int +get_day_diff(struct tm *date) +{ + time_t now; + time(&now); + double sec_diff = difftime(now, mktime(date)); + int day_diff = sec_diff / 3600 / 24; + return day_diff; +} + +struct tm +parse_date(char *date_str) +{ + char year[4], month[3], day[3]; + int i_year, i_mon, i_day; + sscanf(date_str, "%04s-%02s-%02s", year, month, day); + i_year = atoi(year) - 1900; + i_mon = atoi(month) - 1; + i_day = atoi(day); + struct tm date = {.tm_year=i_year, .tm_mon=i_mon, .tm_mday=i_day}; + mktime(&date); + return date; +} + +void +print_days() +{ + char day[3]; + time_t current_time; + current_time = time(NULL); + struct tm *local = localtime(¤t_time); + for (int i = TRACK_LENGTH; i >0; --i) { + local->tm_mday -= i; + mktime(local); + strftime(day, sizeof day, DAY_REPR, local); + printf("%s ", day); + local->tm_mday += i; + } + printf("\n"); +} diff --git a/date.h b/date.h new file mode 100644 index 0000000..fd6c75e --- /dev/null +++ b/date.h @@ -0,0 +1,8 @@ +#ifndef DATE_H +#define DATE_H + +int get_day_diff(struct tm *date); +struct tm parse_date(char *date_str); +void print_days(); + +#endif diff --git a/wochabit.c b/wochabit.c index 028634a..c69cd10 100644 --- a/wochabit.c +++ b/wochabit.c @@ -19,9 +19,11 @@ #include #include #include +#include #include "constants.h" #include "config.h" +#include "date.h" void print_status(int status); // Print the status for a day of a habit void print_habit(int habit); // Print the habit stati during the tracked duration @@ -69,6 +71,13 @@ main(int argc, char *argv[]){ print_habit(5); print_habit(49); print_habit(1 << TRACK_LENGTH - 2); + print_days(); + struct tm date = parse_date("2020-11-19"); + printf("%d\n", date.tm_year); + printf("%d\n", date.tm_mon); + printf("%d\n", date.tm_mday); + int diff = get_day_diff(&date); + printf("%d\n", diff); printf("Bye\n"); return 0; }