The -d
option is not a standard option to date
, and the standard date
specification has no provision for taking a date in one format and reformat it in another format.
BSD, GNU, ast-open and busybox date
have options for that, but with different syntax and of the 4, GNU date
, which you seem to be using given the wording of your error message, is the only one where you can't specify the input format.
So you can't do what you're asking portably with date
alone.
Here, beside resorting to proper programming languages like perl
/python
/tcl
... you could switch from bash
to zsh
which has a builtin interface to strptime()
:
$ zmodload zsh/datetime
$ start='23/07/2021 14:44'
$ strftime -r '%d/%m/%Y %H:%M' $start
1627047840
That gives you the epoch time for that date interpreted as local time (for me, Europe/London time) at 14:44:00. If that timestamp is meant to be in UTC time, change to:
$ TZ=UTC0 strftime -r '%d/%m/%Y %H:%M' $start
1627051440
To store into a scalar variable, you can use the -s
option.
$ strftime -s startSec -r '%d/%m/%Y %H:%M' $start
$ echo $startSec
1627047840
The ksh93 shell can also parse dates with its printf
builtin (or its date
builtin if it was built as part of ast-open, though that's rarely the case these days), though specifying the input format is a bit cumbersome, as you need to store the list of formats in a file specified with the $DATEMSK
variable (as for standard getdate()
), though on systems with /dev/fd/x
, you can do:
$ { DATEMSK=/dev/fd/3 printf '%(%s)T\n' "$start"; } 3<<< '%d/%m/%Y %H:%M'
1627047840
(it doesn't work without the command group with my version of ksh93 (from the Ubuntu 20.04 ksh package), a bug apparently fixed in newer versions from https://github.com/ksh93/ksh).
Note that whilst 23/07/2021 14:44
is most likely unambiguous as a local time in your timezone, with that timestamp format, there are going to be ambiguous ones if your timezone implements DST.
For instance, in my Europe/London timezones there are two possible Unix epoch times that correspond to 25/10/2020 01:30
:
$ strftime '%d/%m/%Y %H:%M' 1603585800
25/10/2020 01:30
$ strftime '%d/%m/%Y %H:%M' 1603589400
25/10/2020 01:30
On my system, zsh's strftime -r
(the system's strptime()
) picks the latter:
$ strftime -r '%d/%m/%Y %H:%M' '25/10/2020 01:30'
1603589400
day/month/year
is not a recognized format. – glenn jackman Jul 23 '21 at 19:18