Display current date and time without punctuation

For example, I want to display the current date and time in the following format:

yyyymmddhhmmss 

How should I do it? It seems that most date formats have - , / , : , etc.

+53
bash shell
Dec 12 '13 at 18:39
source share
3 answers

Here you go:

 date +%Y%m%d%H%M%S 

As man date says near the top, you can use the date command as follows:

  date [OPTION]... [+FORMAT] 

That is, you can specify a format parameter for it, starting with + . You can probably guess the meaning of the formatting characters used:

  • %Y - year
  • %m - within a month
  • %d for the day
  • ... etc.

You can find this and other formatting characters in man date .

+86
Dec 12 '13 at 18:41
source share

A simple example in a shell script

 #!/bin/bash current_date_time="`date +%Y%m%d%H%M%S`"; echo $current_date_time; 

No punctuation: - +% Y% m% d% H% M% S
With punctuation: - +% Y -% m -% d% H:% M:% S

+15
Feb 25 '16 at 6:27
source share

If you use Bash, you can 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 -v varname option to save the result to $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 built-in command and therefore will be faster.

+2
May 16 '17 at 15:08
source share



All Articles