Date: invalid date trying to set Linux date in specific format

i try to set linux date & time in specific format but it keep giving me error
Example :

date "+%d-%m-%C%y %H:%M:%S" -d "19-01-2017 00:05:01"

or

date +"%d-%m-%C%y %H:%M:%S" -d "19-01-2017 00:05:01"

keep giving me this error :

date: invalid date �19-01-2017 00:05:01'

Dates specified with hyphens (-) as delimiters are assumed to be in ISO 8601 format, with the year first, therefore:

$ date "+%d-%m-%C%y %H:%M:%S" -d"2017-01-19 00:05:01"
19-01-2017 00:05:01

So basically 19-01-2017 does not conform to the expected format of [cc]yy-mm-dd and so was rejected.

You could use slashes (/) to delimit the day, month and year, unfortunately date will assume American date format:

$ date "+%d-%m-%C%y %H:%M:%S" -d "12/01/2017 00:05:01"
01-12-2017 00:05:01
$ date "+%d-%m-%C%y %H:%M:%S" -d "19/01/2017 00:05:01"
date: invalid date �19/01/2017 00:05:01'

Personally I would use the year-month-day format.

Andrew

2 Likes

those date are from some third party input so i guess i will need to change the format on the fly

Be aware that date 's + option specifies the output format, not a date string input template.

Do the date strings coming from third party come in a file, or immediately on stdout?

1 Like

immediately on stdout
by invoking remote ssh command

In this case use variable expansion to reformat it to your needs:

yourdate="$(ssh <your ssh-command)"
echo $yourdate
19-01-2017 00:05:01"

mytime="${yourdate#* }"         # extract "00:05:01"
yourdate="${yourdate% *}"       # remove time from date, leaving "19-01-2017"
myyear="${yourdate##*-}"        # extract the year "2017"
yourdate="${yourdate%-*}"       # remove "-${myyear}" from the date leaving "19-01"
mymonth="${yourdate##*-}"       # extract the month "01"
yourdate="${yourdate%-*}"       # remove "-${mymonth}" from the date leaving "19"
myday="${yourdate}"

Using the variables set this way you can easily set your date using a different format.

I hope this helps.

bakunin

1 Like

You might also, if your shell offers "here strings", try

$ IFS="- :" read DAY MTH YR HR MIN SEC <<< "$yourdate"
$ echo $DAY $MTH $YR $HR $MIN $SEC
19 01 2017 00 05 01
$ date -d"$YR-$MTH-$DAY $HR:$MIN:$SEC"
Do 19. Jan 00:05:01 CET 2017
1 Like

The great thing is that in utilities like "date", "sort" there is a "--debug" option that helps to work on the bugs.
In the output with this option, you can immediately see in the first line where the error:

parsed date part: (Y-M-D) 0019-01-2017
warning: adjusting year value 19 to 2019
3 Likes