Last active
May 27, 2019 08:48
-
-
Save ghoomfrog/89061b9d8e47997efa05aac287e0c4c8 to your computer and use it in GitHub Desktop.
Functions to extract the year, the month and the day of a date integer (like 20151126), without using strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Functions to extract the year, the month and the day of a date integer (like 20151126), without using strings. | |
* | |
* by Unlimiter | |
*/ | |
#include <stdio.h> | |
#include <math.h> | |
// returns the number of digits in an integer | |
int get_int_len(int n) { | |
return ceil(log10(n)); | |
} | |
// returns 10**(n-1) | |
int int_to_ten_power(int n) { | |
if (n == 0) { | |
return 0; | |
} | |
int one_and_zeros = 1; | |
for (int i = 1; i < n; i++) { | |
one_and_zeros *= 10; | |
} | |
return one_and_zeros; | |
} | |
// returns the yyyy part of an integer, as in yyyymmdd | |
int get_year(int d) { | |
return d/((int_to_ten_power(get_int_len(d))/int_to_ten_power(4))); | |
} | |
// returns the mm part of an integer, as in yyyymmdd | |
int get_month(int d) { | |
return (d - get_year(d) * 10000) / 100; | |
} | |
// returns the dd part of an integer, as in yyyymmdd | |
int get_day(int d) { | |
return (d - get_year(d) * 10000) - (get_month(d) * 100); | |
} | |
// demo | |
int main() { | |
int date = 20190413; | |
printf("%i-0%i-%i\n", get_year(date), get_month(date), get_day(date)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment