5 * Implements the clock command
10 #define _XOPEN_SOURCE 500
20 #include "jimautoconf.h"
21 #include "jim-subcmd.h"
23 static int clock_cmd_format(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
25 /* How big is big enough? */
30 const char *format
= "%a %b %d %H:%M:%S %Z %Y";
32 if (argc
== 2 || (argc
== 3 && !Jim_CompareStringImmediate(interp
, argv
[1], "-format"))) {
37 format
= Jim_String(argv
[2]);
40 if (Jim_GetLong(interp
, argv
[0], &seconds
) != JIM_OK
) {
45 strftime(buf
, sizeof(buf
), format
, localtime(&t
));
47 Jim_SetResultString(interp
, buf
, -1);
53 static int clock_cmd_scan(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
59 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-format")) {
63 /* Initialise with the current date/time */
64 localtime_r(&now
, &tm
);
66 pt
= strptime(Jim_String(argv
[0]), Jim_String(argv
[2]), &tm
);
67 if (pt
== 0 || *pt
!= 0) {
68 Jim_SetResultString(interp
, "Failed to parse time according to format", -1);
72 /* Now convert into a time_t */
73 Jim_SetResultInt(interp
, mktime(&tm
));
79 static int clock_cmd_seconds(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
81 Jim_SetResultInt(interp
, time(NULL
));
86 static int clock_cmd_micros(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
90 gettimeofday(&tv
, NULL
);
92 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
);
97 static int clock_cmd_millis(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
101 gettimeofday(&tv
, NULL
);
103 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000);
108 static const jim_subcmd_type clock_command_table
[] = {
110 .function
= clock_cmd_seconds
,
113 .description
= "Returns the current time as seconds since the epoch"
116 .function
= clock_cmd_micros
,
119 .description
= "Returns the current time in 'clicks'"
121 { .cmd
= "microseconds",
122 .function
= clock_cmd_micros
,
125 .description
= "Returns the current time in microseconds"
127 { .cmd
= "milliseconds",
128 .function
= clock_cmd_millis
,
131 .description
= "Returns the current time in milliseconds"
134 .args
= "seconds ?-format format?",
135 .function
= clock_cmd_format
,
138 .description
= "Format the given time"
142 .args
= "str -format format",
143 .function
= clock_cmd_scan
,
146 .description
= "Determine the time according to the given format"
152 int Jim_clockInit(Jim_Interp
*interp
)
154 if (Jim_PackageProvide(interp
, "clock", "1.0", JIM_ERRMSG
))
157 Jim_CreateCommand(interp
, "clock", Jim_SubCmdProc
, (void *)clock_command_table
, NULL
);