For example, I want to display current date and time as the following format:
yyyymmddhhmmss
How do I do that? It seems like most date format comes with -
, /
, :
, etc.
Here you go:
date +%Y%m%d%H%M%S
As man date
says near the top, you can use the date
command like this:
date [OPTION]... [+FORMAT]
That is, you can give it a format parameter, starting with a +
.
You can probably guess the meaning of the formatting symbols I used:
%Y
is for year%m
is for month%d
is for dayYou can find this, and other formatting symbols in man date
.
A simple example in shell script
#!/bin/bash
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S
"`date +%Y-%m-%d %H:%M:%S`"
gives me a date: illegal time format
Without punctuation (as @Burusothman has mentioned):
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
O/P:
20170115072120
With punctuation:
current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;
O/P:
2017-01-15 07:25:33
If you're using Bash you could also use one of the following commands:
printf '%(%Y%m%d%H%M%S)T' # prints the current time
printf '%(%Y%m%d%H%M%S)T' -1 # same as above
printf '%(%Y%m%d%H%M%S)T' -2 # prints the time the shell was invoked
You can use the Option -v varname
to store the result in $varname
instead of printing it to stdout:
printf -v varname '%(%Y%m%d%H%M%S)T'
While the date command will always be executed in a subshell (i.e. in a separate process) printf is a builtin command and will therefore be faster.
%
options you can pass in, this seems to be using the date
command. So, man date
will give you the available options.
Commented
Dec 10, 2019 at 0:00
Interesting/funny way to do this using parameter expansion (requires bash 4.4
or newer):
${parameter@operator} - P operator
The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.
$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251