Skip to main content
Catch `date` adjusting for times such as 2015-20-06 (YYYY-MM-DD, really)
Source Link
Chris Davies
  • 128.4k
  • 16
  • 179
  • 324

The reason your test fails is because the condition test uses a value of $? that is non-zero. The reason it's non-zero is because date is producing a non-zero exit status. If you temporarily stop discarding date's stderr with the > /dev/null 2>&1 you'll get to see the error message it's producing. That will help you identify the issue.

date: invalid date ‘20150620223405’

What date is saying is that your date format is not acceptable.

You could try this:

a=20150620223405
b=$(echo "$a" | sed 's/^\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1-\2-\3 \4:\5:\6/')
c=$(date "+%Y%m%d%H%M%S" -d "$b" 2>/dev/null)
if test $? -eq 0 -a "$c" = "$a"
then
    echo ok
else
    echo not ok
fi

The reason your test fails is because the condition test uses a value of $? that is non-zero. The reason it's non-zero is because date is producing a non-zero exit status. If you temporarily stop discarding date's stderr with the > /dev/null 2>&1 you'll get to see the error message it's producing. That will help you identify the issue.

date: invalid date ‘20150620223405’

What date is saying is that your date format is not acceptable.

You could try this:

a=20150620223405
b=$(echo "$a" | sed 's/^\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1-\2-\3 \4:\5:\6/')
date "+%Y%m%d%H%M%S" -d "$b"

The reason your test fails is because the condition test uses a value of $? that is non-zero. The reason it's non-zero is because date is producing a non-zero exit status. If you temporarily stop discarding date's stderr with the > /dev/null 2>&1 you'll get to see the error message it's producing. That will help you identify the issue.

date: invalid date ‘20150620223405’

What date is saying is that your date format is not acceptable.

You could try this:

a=20150620223405
b=$(echo "$a" | sed 's/^\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1-\2-\3 \4:\5:\6/')
c=$(date "+%Y%m%d%H%M%S" -d "$b" 2>/dev/null)
if test $? -eq 0 -a "$c" = "$a"
then
    echo ok
else
    echo not ok
fi
Source Link
Chris Davies
  • 128.4k
  • 16
  • 179
  • 324

The reason your test fails is because the condition test uses a value of $? that is non-zero. The reason it's non-zero is because date is producing a non-zero exit status. If you temporarily stop discarding date's stderr with the > /dev/null 2>&1 you'll get to see the error message it's producing. That will help you identify the issue.

date: invalid date ‘20150620223405’

What date is saying is that your date format is not acceptable.

You could try this:

a=20150620223405
b=$(echo "$a" | sed 's/^\(....\)\(..\)\(..\)\(..\)\(..\)\(..\)$/\1-\2-\3 \4:\5:\6/')
date "+%Y%m%d%H%M%S" -d "$b"