aio recvfrom was not null terminating the result
[jimtcl.git] / jim-clock.c
blob20955c7812aeefbf3ee3fe9fc50075f502f98f04
2 /*
3 * tcl_clock.c
5 * Implements the clock command
6 */
8 /* For strptime() */
9 #define _XOPEN_SOURCE
11 #include <stdlib.h>
12 #include <string.h>
13 #include <stdio.h>
14 #include <time.h>
16 #include "jim.h"
17 #include "jim-subcmd.h"
19 static int clock_cmd_format(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
21 /* How big is big enough? */
22 char buf[100];
23 time_t t;
24 long seconds;
26 const char *format = "%a %b %d %H:%M:%S %Z %Y";
28 if (argc == 2 || (argc == 3 && !Jim_CompareStringImmediate(interp, argv[1], "-format"))) {
29 return -1;
32 if (argc == 3) {
33 format = Jim_GetString(argv[2], NULL);
36 if (Jim_GetLong(interp, argv[0], &seconds) != JIM_OK) {
37 return JIM_ERR;
39 t = seconds;
41 strftime(buf, sizeof(buf), format, localtime(&t));
43 Jim_SetResultString(interp, buf, -1);
45 return JIM_OK;
48 #ifdef HAVE_STRPTIME
49 static int clock_cmd_scan(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
51 char *pt;
52 struct tm tm;
53 time_t now = time(0);
55 if (!Jim_CompareStringImmediate(interp, argv[1], "-format")) {
56 return -1;
59 /* Initialise with the current date/time */
60 tm = *localtime(&now);
62 pt = strptime(Jim_GetString(argv[0], NULL), Jim_GetString(argv[2], NULL), &tm);
63 if (pt == 0 || *pt != 0) {
64 Jim_SetResultString(interp, "Failed to parse time according to format", -1);
65 return JIM_ERR;
68 /* Now convert into a time_t */
69 Jim_SetResultInt(interp, mktime(&tm));
71 return JIM_OK;
73 #endif
75 static int clock_cmd_seconds(Jim_Interp *interp, int argc, Jim_Obj *const *argv)
77 Jim_SetResultInt(interp, time(NULL));
79 return JIM_OK;
82 static const jim_subcmd_type clock_command_table[] = {
83 { .cmd = "seconds",
84 .function = clock_cmd_seconds,
85 .minargs = 0,
86 .maxargs = 0,
87 .description = "Returns the current time as seconds since the epoch"
89 { .cmd = "format",
90 .args = "seconds ?-format format?",
91 .function = clock_cmd_format,
92 .minargs = 1,
93 .maxargs = 3,
94 .description = "Format the given time"
96 #ifdef HAVE_STRPTIME
97 { .cmd = "scan",
98 .args = "str -format format",
99 .function = clock_cmd_scan,
100 .minargs = 3,
101 .maxargs = 3,
102 .description = "Determine the time according to the given format"
104 #endif
105 { 0 }
108 int Jim_clockInit(Jim_Interp *interp)
110 Jim_CreateCommand(interp, "clock", Jim_SubCmdProc, (void *)clock_command_table, NULL);
111 return JIM_OK;