5 * Implements the clock command
10 #define _XOPEN_SOURCE 500
19 #include "jimautoconf.h"
20 #include "jim-subcmd.h"
22 #ifdef HAVE_SYS_TIME_H
26 static int clock_cmd_format(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
28 /* How big is big enough? */
33 const char *format
= "%a %b %d %H:%M:%S %Z %Y";
35 if (argc
== 2 || (argc
== 3 && !Jim_CompareStringImmediate(interp
, argv
[1], "-format"))) {
40 format
= Jim_String(argv
[2]);
43 if (Jim_GetLong(interp
, argv
[0], &seconds
) != JIM_OK
) {
48 strftime(buf
, sizeof(buf
), format
, localtime(&t
));
50 Jim_SetResultString(interp
, buf
, -1);
56 static int clock_cmd_scan(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
62 if (!Jim_CompareStringImmediate(interp
, argv
[1], "-format")) {
66 /* Initialise with the current date/time */
67 localtime_r(&now
, &tm
);
69 pt
= strptime(Jim_String(argv
[0]), Jim_String(argv
[2]), &tm
);
70 if (pt
== 0 || *pt
!= 0) {
71 Jim_SetResultString(interp
, "Failed to parse time according to format", -1);
75 /* Now convert into a time_t */
76 Jim_SetResultInt(interp
, mktime(&tm
));
82 static int clock_cmd_seconds(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
84 Jim_SetResultInt(interp
, time(NULL
));
89 static int clock_cmd_micros(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
93 gettimeofday(&tv
, NULL
);
95 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000000 + tv
.tv_usec
);
100 static int clock_cmd_millis(Jim_Interp
*interp
, int argc
, Jim_Obj
*const *argv
)
104 gettimeofday(&tv
, NULL
);
106 Jim_SetResultInt(interp
, (jim_wide
) tv
.tv_sec
* 1000 + tv
.tv_usec
/ 1000);
111 static const jim_subcmd_type clock_command_table
[] = {
117 /* Description: Returns the current time as seconds since the epoch */
124 /* Description: Returns the current time in 'clicks' */
131 /* Description: Returns the current time in microseconds */
138 /* Description: Returns the current time in milliseconds */
141 "seconds ?-format format?",
145 /* Description: Format the given time */
149 "str -format format",
153 /* Description: Determine the time according to the given format */
159 int Jim_clockInit(Jim_Interp
*interp
)
161 if (Jim_PackageProvide(interp
, "clock", "1.0", JIM_ERRMSG
))
164 Jim_CreateCommand(interp
, "clock", Jim_SubCmdProc
, (void *)clock_command_table
, NULL
);