/* * Copyright (C) 2021 P. J. McDermott * * This file is part of @ * * @ is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * @ is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with @. If not, see . */ #define _XOPEN_SOURCE #include #include #include #include #include "datetime.h" static const char *DATETIME_FMTS_[] = { #include "datetime-formats.c" NULL }; int datetime_parse(const char *input, time_t *arg_sec) { int i; char *end; struct tm arg_tm; time_t now_sec; struct tm *now_tm; arg_tm.tm_mday = INT_MIN; /* Sentinel */ arg_tm.tm_sec = 0; /* Default */ arg_tm.tm_isdst = -1; for (i = 0; DATETIME_FMTS_[i] != NULL; ++i) { end = strptime(input, DATETIME_FMTS_[i], &arg_tm); if (end != NULL && *end == '\0') { goto found; } } fprintf(stderr, "Unknown date format\n"); return -1; found: /* TODO: Support %a-only dates and optional years */ if (arg_tm.tm_mday == INT_MIN) { /* No date specified; try today. */ now_sec = time(NULL); now_tm = localtime(&now_sec); arg_tm.tm_year = now_tm->tm_year; arg_tm.tm_mon = now_tm->tm_mon; arg_tm.tm_mday = now_tm->tm_mday; *arg_sec = mktime(&arg_tm); if (*arg_sec <= mktime(now_tm)) { /* Specified time already happened today; use tomorrow. * Adding the number of seconds in a day is a shortcut * that ignores leap seconds. One better method would * be to increment tm_mday % days in tm_mon, etc. */ *arg_sec += 60 * 60 * 24; now_tm = localtime(arg_sec); arg_tm.tm_year = now_tm->tm_year; arg_tm.tm_mon = now_tm->tm_mon; arg_tm.tm_mday = now_tm->tm_mday; *arg_sec = mktime(&arg_tm); } } else { *arg_sec = mktime(&arg_tm); } return 0; }