nsh_timcmds: display date using set format

Reference: https://www.geeksforgeeks.org/date-command-linux-examples/?ref=gcse#9-list-of-format-specifiers-used-with-date-command

Signed-off-by: yangjian11 <yangjian11@xiaomi.com>
This commit is contained in:
yangjian11 2024-01-26 11:04:33 +08:00 committed by Xiang Xiao
parent 61d1f37f5f
commit 09122debe9
2 changed files with 18 additions and 6 deletions

View File

@ -182,7 +182,7 @@ static const struct cmdmap_s g_cmdmap[] =
#ifndef CONFIG_NSH_DISABLE_DATE
CMD_MAP("date", cmd_date,
1, 4, "[-s \"MMM DD HH:MM:SS YYYY\"] [-u]"),
1, 4, "[-s \"MMM DD HH:MM:SS YYYY\"] [-u] [+format]"),
#endif
#ifndef CONFIG_NSH_DISABLE_DD

View File

@ -95,7 +95,8 @@ static inline int date_month(FAR const char *abbrev)
#ifndef CONFIG_NSH_DISABLE_DATE
static inline int date_showtime(FAR struct nsh_vtbl_s *vtbl,
FAR const char *name, bool utc)
FAR const char *name, bool utc,
FAR const char *format)
{
struct timespec ts;
struct tm tm;
@ -132,7 +133,7 @@ static inline int date_showtime(FAR struct nsh_vtbl_s *vtbl,
/* Show the current time in the requested format */
ret = strftime(timbuf, MAX_TIME_STRING, "%a, %b %d %H:%M:%S %Y", &tm);
ret = strftime(timbuf, MAX_TIME_STRING, format, &tm);
if (ret < 0)
{
nsh_error(vtbl, g_fmtcmdfailed, name, "strftime", NSH_ERRNO);
@ -367,6 +368,7 @@ int cmd_time(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
{
FAR char *newtime = NULL;
FAR const char *format = "%a, %b %d %H:%M:%S %Y";
FAR const char *errfmt;
bool utc = false;
int option;
@ -395,11 +397,21 @@ int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
}
}
/* optind < argc-1 means that there are additional, unexpected arguments on
argc -= optind;
/* Display the time according to the format we set */
if (argv[optind] && *argv[optind] == '+')
{
format = argv[optind] + 1;
argc--;
}
/* argc > 0 means that there are additional, unexpected arguments on
* th command-line
*/
if (optind < argc)
if (argc > 0)
{
errfmt = g_fmttoomanyargs;
goto errout;
@ -413,7 +425,7 @@ int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
}
else
{
ret = date_showtime(vtbl, argv[0], utc);
ret = date_showtime(vtbl, argv[0], utc, format);
}
return ret;