File: strtoday.c

package info (click to toggle)
shadow 1%3A4.18.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 66,920 kB
  • sloc: sh: 44,121; ansic: 34,155; xml: 12,285; exp: 3,691; makefile: 1,650; python: 1,135; perl: 120; sed: 16
file content (77 lines) | stat: -rw-r--r-- 1,356 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// SPDX-FileCopyrightText: 1991-1994, Julianne Frances Haugh
// SPDX-FileCopyrightText: 1996-1999, Marek Michałkiewicz
// SPDX-FileCopyrightText: 2003-2005, Tomasz Kłoczko
// SPDX-FileCopyrightText: 2008, Nicolas François
// SPDX-FileCopyrightText: 2025, Alejandro Colomar <alx@kernel.org>
// SPDX-FileCopyrightText: 2025, "Haelwenn (lanodan) Monnier" <contact@hacktivis.me>
// SPDX-License-Identifier: BSD-3-Clause


#include <config.h>

#include <stddef.h>
#include <time.h>

#include "atoi/str2i.h"
#include "defines.h"
#include "prototypes.h"
#include "string/strcmp/streq.h"


static long get_date(const char *s);
static long dategm(struct tm *tm);


// string parse-to day-since-Epoch
long
strtoday(const char *str)
{
	long  d;

	if (NULL == str || streq(str, ""))
		return -1;

	/* If a numerical value is provided, this is already a number of
	 * days since EPOCH.
	 */
	if (str2sl(&d, str) == 0)
		return d;

	d = get_date(str);
	if (d == -1)
		return -2;

	return d;
}


static long
get_date(const char *s)
{
	time_t      t;
	struct tm   tm;
	const char  *p;

	t = 0;
	if (gmtime_r(&t, &tm) == NULL)
		return -1;

	p = strptime(s, "%Y-%m-%d", &tm);
	if (p == NULL || !streq(p, ""))
		return -1;

	return dategm(&tm);
}


static long
dategm(struct tm *tm)
{
	time_t  t;

	t = timegm(tm);
	if (t == (time_t) -1)
		return -1;

	return t / DAY;
}