4 * Implements the clock command
9 #define _XOPEN_SOURCE 500
17 #include "jimautoconf.h"
18 #include <jim-subcmd.h>
20 #ifdef HAVE_SYS_TIME_H
24 static int clock_cmd_format(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
26 /* How big is big enough? */
31 const char *format
= "%a %b %d %H:%M:%S %Z %Y";
33 if (argc
== 2 || (argc
== 3 && !Jim_CompareStringImmediate(interp
, argv
[1], "-format"))) {
38 format
= Jim_String(argv
[2]);
41 if (Jim_GetLong(interp
, argv
[0], &seconds
) != JIM_OK
) {
46 if (strftime(buf
, sizeof(buf
), format
, localtime(&t
)) == 0) {
47 Jim_SetResultString(interp
, "format string too long", -1);
51 Jim_SetResultString(interp
, buf
, -1);
57 static int clock_cmd_scan(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
63 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-format")) {
67 /* Initialise with the current date/time */
68 localtime_r(&now
, &tm
);
70 pt
= strptime(Jim_String(argv
[0]), Jim_String(argv
[2]), &tm
);
71 if (pt
== 0 || *pt
!= 0) {
72 Jim_SetResultString(interp
, "Failed to parse time according to format", -1);
76 /* Now convert into a time_t */
77 Jim_SetResultInt(interp
, mktime(&tm
));
83 static int clock_cmd_seconds(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
85 Jim_SetResultInt(interp
, time(NULL
));
90 static int clock_cmd_micros(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
94 gettimeofday(&tv
, NULL
);
96 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
);
101 static int clock_cmd_millis(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
105 gettimeofday(&tv
, NULL
);
107 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000);
112 static const jim_subcmd_type clock_command_table
[] = {
118 /* Description: Returns the current time as seconds since the epoch */
125 /* Description: Returns the current time in 'clicks' */
132 /* Description: Returns the current time in microseconds */
139 /* Description: Returns the current time in milliseconds */
142 "seconds ?-format format?",
146 /* Description: Format the given time */
150 "str -format format",
154 /* Description: Determine the time according to the given format */
160 int Jim_clockInit(Jim_Interp
*interp
)
162 if (Jim_PackageProvide(interp
, "clock", "1.0", JIM_ERRMSG
))
165 Jim_CreateCommand(interp
, "clock", Jim_SubCmdProc
, (void *)clock_command_table
, NULL
);