/*
Copyright (C) 2018 Assaf Gordon
License: public domain.
Example of date arithmetics, related to discussion in
https://lists.gnu.org/archive/html/bug-coreutils/2018-02/msg00002.html
Explaining why:
$ date +%Y-%m-%d -d '2003-02-01 - 31 days + 1 month'
2003-01-29
Compile with:
gcc -o date-arith date-arith.c
*/
#include
#include
#include
#include
int main()
{
struct tm a;
time_t t;
memset (&a, 0, sizeof a);
/* Date is "2003-02-01 - 31 days + 1 month" */
a.tm_year = 103; /* years since 1900 */
a.tm_mon = 1 + 1 ; /* 0=jan, 1=feb .. 11=dec */
a.tm_mday = 1 - 31 ; /* day-of-month: 1 to 31 */
printf("before: %04d-%02d-%02d\n",a.tm_year+1900,a.tm_mon+1,a.tm_mday);
/* call libc to check and normalize the values in 'struct tm'.
POSIX specifically says:
http://pubs.opengroup.org/onlinepubs/7908799/xsh/mktime.html
"The original values of the tm_wday and tm_yday components of the
structure are ignored, and the original values of the other
components are not restricted to the ranges described in
the entry."
Therefore "tm_mday=-30" is a valid value which will be normalized.
(error checking ommited for brevity).
*/
t = mktime (&a);
/* Now convert back to struct tm */
localtime_r (&t, &a);
printf("after: %04d-%02d-%02d\n",a.tm_year+1900,a.tm_mon+1,a.tm_mday);
return 0;
}