Skip to content

Commit 09122de

Browse files
maxyjianxiaoxiang781216
authored andcommitted
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>
1 parent 61d1f37 commit 09122de

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

nshlib/nsh_command.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,7 +182,7 @@ static const struct cmdmap_s g_cmdmap[] =
182182

183183
#ifndef CONFIG_NSH_DISABLE_DATE
184184
CMD_MAP("date", cmd_date,
185-
1, 4, "[-s \"MMM DD HH:MM:SS YYYY\"] [-u]"),
185+
1, 4, "[-s \"MMM DD HH:MM:SS YYYY\"] [-u] [+format]"),
186186
#endif
187187

188188
#ifndef CONFIG_NSH_DISABLE_DD

nshlib/nsh_timcmds.c

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,8 @@ static inline int date_month(FAR const char *abbrev)
9595

9696
#ifndef CONFIG_NSH_DISABLE_DATE
9797
static inline int date_showtime(FAR struct nsh_vtbl_s *vtbl,
98-
FAR const char *name, bool utc)
98+
FAR const char *name, bool utc,
99+
FAR const char *format)
99100
{
100101
struct timespec ts;
101102
struct tm tm;
@@ -132,7 +133,7 @@ static inline int date_showtime(FAR struct nsh_vtbl_s *vtbl,
132133

133134
/* Show the current time in the requested format */
134135

135-
ret = strftime(timbuf, MAX_TIME_STRING, "%a, %b %d %H:%M:%S %Y", &tm);
136+
ret = strftime(timbuf, MAX_TIME_STRING, format, &tm);
136137
if (ret < 0)
137138
{
138139
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)
367368
int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
368369
{
369370
FAR char *newtime = NULL;
371+
FAR const char *format = "%a, %b %d %H:%M:%S %Y";
370372
FAR const char *errfmt;
371373
bool utc = false;
372374
int option;
@@ -395,11 +397,21 @@ int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
395397
}
396398
}
397399

398-
/* optind < argc-1 means that there are additional, unexpected arguments on
400+
argc -= optind;
401+
402+
/* Display the time according to the format we set */
403+
404+
if (argv[optind] && *argv[optind] == '+')
405+
{
406+
format = argv[optind] + 1;
407+
argc--;
408+
}
409+
410+
/* argc > 0 means that there are additional, unexpected arguments on
399411
* th command-line
400412
*/
401413

402-
if (optind < argc)
414+
if (argc > 0)
403415
{
404416
errfmt = g_fmttoomanyargs;
405417
goto errout;
@@ -413,7 +425,7 @@ int cmd_date(FAR struct nsh_vtbl_s *vtbl, int argc, FAR char **argv)
413425
}
414426
else
415427
{
416-
ret = date_showtime(vtbl, argv[0], utc);
428+
ret = date_showtime(vtbl, argv[0], utc, format);
417429
}
418430

419431
return ret;

0 commit comments

Comments
 (0)