80 lines
2.4 KiB
C
80 lines
2.4 KiB
C
/* *****************************************************************************
|
|
* utils/date.c -- decode and encode a date.
|
|
* Copyright (C) 2017 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
|
|
*
|
|
* This file is part of libg1m.
|
|
* libg1m is free software; you can redistribute it and/or modify it
|
|
* under the terms of the GNU Lesser General Public License as published by
|
|
* the Free Software Foundation; either version 3.0 of the License,
|
|
* or (at your option) any later version.
|
|
*
|
|
* libg1m 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 Lesser General Public License for more details.
|
|
*
|
|
* You should have received a copy of the GNU Lesser General Public License
|
|
* along with libg1m; if not, see <http://www.gnu.org/licenses/>.
|
|
* ************************************************************************** */
|
|
#include <libg1m/internals.h>
|
|
#include <ctype.h>
|
|
|
|
/**
|
|
* g1m_decode_date:
|
|
* Decode a date from a string.
|
|
*
|
|
* @arg c the raw string.
|
|
* @arg t the destination timestamp.
|
|
* @return the error code (0 if ok).
|
|
*/
|
|
|
|
int g1m_decode_date(const char *c, time_t *t)
|
|
{
|
|
/* checks */
|
|
if (memchr(c, 0, 14)) return (g1m_error_op);
|
|
if (!isdigit(c[0]) || !isdigit(c[1]) || !isdigit(c[2])
|
|
|| !isdigit(c[3]) || c[4] != '.'
|
|
|| !isdigit(c[5]) || !isdigit(c[6]) || !isdigit(c[7])
|
|
|| !isdigit(c[8]) || c[9] != '.'
|
|
|| !isdigit(c[10]) || !isdigit(c[11]) || !isdigit(c[12])
|
|
|| !isdigit(c[13]))
|
|
return (g1m_error_op);
|
|
|
|
/* helper values */
|
|
const int two = '0' + '0' * 10;
|
|
const int four = two + '0' * 100 + '0' * 1000;
|
|
|
|
/* get the tm structure */
|
|
struct tm date = {
|
|
.tm_year = c[0] * 1000 + c[1] * 100 + c[2] * 10 + c[3] - four - 1900,
|
|
.tm_mon = c[5] * 10 + c[6] - two - 1,
|
|
.tm_mday = c[7] * 10 + c[8] - two,
|
|
.tm_hour = c[10] * 10 + c[11] - two,
|
|
.tm_min = c[12] * 10 + c[13] - two
|
|
};
|
|
|
|
/* set the timestamp, return */
|
|
*t = mktime(&date);
|
|
return (0);
|
|
}
|
|
|
|
/**
|
|
* g1m_encode_date:
|
|
* Encode a date from a string.
|
|
*
|
|
* @arg t the source timestamp.
|
|
* @arg c the destination string.
|
|
* @return the error code (0 if ok).
|
|
*/
|
|
|
|
int g1m_encode_date(const time_t *t, char *c)
|
|
{
|
|
/* helper values */
|
|
struct tm *date = gmtime(t);
|
|
char buf[15]; sprintf(buf, "%04u.%02u%02u.%02u%02u",
|
|
min(date->tm_year + 1900, 9999), date->tm_mon + 1, date->tm_mday,
|
|
date->tm_hour, date->tm_min);
|
|
memcpy(c, buf, 14);
|
|
return (0);
|
|
}
|