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
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
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.
Source: Stackoverflow.com