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 strftime(buf
, sizeof(buf
), format
, localtime(&t
));
49 Jim_SetResultString(interp
, buf
, -1);
55 static int clock_cmd_scan(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
61 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-format")) {
65 /* Initialise with the current date/time */
66 localtime_r(&now
, &tm
);
68 pt
= strptime(Jim_String(argv
[0]), Jim_String(argv
[2]), &tm
);
69 if (pt
== 0 || *pt
!= 0) {
70 Jim_SetResultString(interp
, "Failed to parse time according to format", -1);
74 /* Now convert into a time_t */
75 Jim_SetResultInt(interp
, mktime(&tm
));
81 static int clock_cmd_seconds(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
83 Jim_SetResultInt(interp
, time(NULL
));
88 static int clock_cmd_micros(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
92 gettimeofday(&tv
, NULL
);
94 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
);
99 static int clock_cmd_millis(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
103 gettimeofday(&tv
, NULL
);
105 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000);
110 static const jim_subcmd_type clock_command_table
[] = {
116 /* Description: Returns the current time as seconds since the epoch */
123 /* Description: Returns the current time in 'clicks' */
130 /* Description: Returns the current time in microseconds */
137 /* Description: Returns the current time in milliseconds */
140 "seconds ?-format format?",
144 /* Description: Format the given time */
148 "str -format format",
152 /* Description: Determine the time according to the given format */
158 int Jim_clockInit(Jim_Interp
*interp
)
160 if (Jim_PackageProvide(interp
, "clock", "1.0", JIM_ERRMSG
))
163 Jim_CreateCommand(interp
, "clock", Jim_SubCmdProc
, (void *)clock_command_table
, NULL
);