xref: /freebsd/sys/contrib/openzfs/lib/libspl/timestamp.c (revision 22649d4dba730d46244fd2dff4fd174903c8379f)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * This file and its contents are supplied under the terms of the
4  * Common Development and Distribution License ("CDDL"), version 1.0.
5  * You may only use this file in accordance with the terms of version
6  * 1.0 of the CDDL.
7  *
8  * A full copy of the text of the CDDL should have accompanied this
9  * source.  A copy of the CDDL is also available via the Internet at
10  * https://opensource.org/license/CDDL-1.0.
11  */
12 /*
13  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
14  * Use is subject to license terms.
15  */
16 
17 #include <stdio.h>
18 #include <time.h>
19 #include <langinfo.h>
20 #include "statcommon.h"
21 
22 #ifndef _DATE_FMT
23 #ifdef D_T_FMT
24 #define	_DATE_FMT D_T_FMT
25 #else /* D_T_FMT */
26 #define	_DATE_FMT "%+"
27 #endif /* !D_T_FMT */
28 #endif /* _DATE_FMT */
29 
30 /*
31  * Print timestamp as decimal reprentation of time_t value (-T u was specified)
32  * or in date(1) format (-T d was specified).
33  */
34 void
print_timestamp(uint_t timestamp_fmt)35 print_timestamp(uint_t timestamp_fmt)
36 {
37 	time_t t = time(NULL);
38 	static const char *fmt = NULL;
39 
40 	/* We only need to retrieve this once per invocation */
41 	if (fmt == NULL)
42 		fmt = nl_langinfo(_DATE_FMT);
43 
44 	if (timestamp_fmt == UDATE) {
45 		(void) printf("%lld\n", (longlong_t)t);
46 	} else if (timestamp_fmt == DDATE) {
47 		char dstr[64];
48 		struct tm tm;
49 		int len;
50 
51 		len = strftime(dstr, sizeof (dstr), fmt, localtime_r(&t, &tm));
52 		if (len > 0)
53 			(void) printf("%s\n", dstr);
54 	}
55 }
56 
57 /*
58  * Return timestamp as decimal reprentation (in string) of time_t
59  * value (-T u was specified) or in date(1) format (-T d was specified).
60  */
61 void
get_timestamp(uint_t timestamp_fmt,char * buf,int len)62 get_timestamp(uint_t timestamp_fmt, char *buf, int len)
63 {
64 	time_t t = time(NULL);
65 	static const char *fmt = NULL;
66 
67 	/* We only need to retrieve this once per invocation */
68 	if (fmt == NULL)
69 		fmt = nl_langinfo(_DATE_FMT);
70 
71 	if (timestamp_fmt == UDATE) {
72 		(void) snprintf(buf, len, "%lld", (longlong_t)t);
73 	} else if (timestamp_fmt == DDATE) {
74 		struct tm tm;
75 		strftime(buf, len, fmt, localtime_r(&t, &tm));
76 	}
77 }
78 
79 /*
80  * Format the provided time stamp to human readable format
81  */
82 void
format_timestamp(time_t t,char * buf,int len)83 format_timestamp(time_t t, char *buf, int len)
84 {
85 	struct tm tm;
86 	static const char *fmt = NULL;
87 
88 	if (t == 0) {
89 		snprintf(buf, len, "-");
90 		return;
91 	}
92 
93 	/* We only need to retrieve this once per invocation */
94 	if (fmt == NULL)
95 		fmt = nl_langinfo(_DATE_FMT);
96 	strftime(buf, len, fmt, localtime_r(&t, &tm));
97 }
98