5 * Implements the clock command
10 #define _XOPEN_SOURCE 500
18 #include "jimautoconf.h"
19 #include <jim-subcmd.h>
21 #ifdef HAVE_SYS_TIME_H
25 static int clock_cmd_format(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
27 /* How big is big enough? */
32 const char *format
= "%a %b %d %H:%M:%S %Z %Y";
34 if (argc
== 2 || (argc
== 3 && !Jim_CompareStringImmediate(interp
, argv
[1], "-format"))) {
39 format
= Jim_String(argv
[2]);
42 if (Jim_GetLong(interp
, argv
[0], &seconds
) != JIM_OK
) {
47 if (strftime(buf
, sizeof(buf
), format
, localtime(&t
)) == 0) {
48 Jim_SetResultString(interp
, "format string too long", -1);
52 Jim_SetResultString(interp
, buf
, -1);
58 static int clock_cmd_scan(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
64 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-format")) {
68 /* Initialise with the current date/time */
69 localtime_r(&now
, &tm
);
71 pt
= strptime(Jim_String(argv
[0]), Jim_String(argv
[2]), &tm
);
72 if (pt
== 0 || *pt
!= 0) {
73 Jim_SetResultString(interp
, "Failed to parse time according to format", -1);
77 /* Now convert into a time_t */
78 Jim_SetResultInt(interp
, mktime(&tm
));
84 static int clock_cmd_seconds(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
86 Jim_SetResultInt(interp
, time(NULL
));
91 static int clock_cmd_micros(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
95 gettimeofday(&tv
, NULL
);
97 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
);
102 static int clock_cmd_millis(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
106 gettimeofday(&tv
, NULL
);
108 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000);
113 static const jim_subcmd_type clock_command_table
[] = {
119 /* Description: Returns the current time as seconds since the epoch */
126 /* Description: Returns the current time in 'clicks' */
133 /* Description: Returns the current time in microseconds */
140 /* Description: Returns the current time in milliseconds */
143 "seconds ?-format format?",
147 /* Description: Format the given time */
151 "str -format format",
155 /* Description: Determine the time according to the given format */
161 int Jim_clockInit(Jim_Interp
*interp
)
163 if (Jim_PackageProvide(interp
, "clock", "1.0", JIM_ERRMSG
))
166 Jim_CreateCommand(interp
, "clock", Jim_SubCmdProc
, (void *)clock_command_table
, NULL
);