Display current date and time without punctuation

BashShellDate

Bash Problem Overview


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.

Bash Solutions


Solution 1 - Bash

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 day
  • ... and so on

You can find this, and other formatting symbols in man date.

Solution 2 - Bash

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

Solution 3 - Bash

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

Solution 4 - Bash

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.

Solution 5 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionreturn 0View Question on Stackoverflow
Solution 1 - BashjanosView Answer on Stackoverflow
Solution 2 - BashBruceView Answer on Stackoverflow
Solution 3 - BashAni MenonView Answer on Stackoverflow
Solution 4 - BashafallerView Answer on Stackoverflow
Solution 5 - BashPesaTheView Answer on Stackoverflow