Date format conversion function

Hello,

does somebody knows about a function that would convert a date like:

YYMMDD into a date like YYYY-MM-DD ?

Thank you for your ideas

:slight_smile:

yes, one of the 'functions' is 'sed'

I can have either :

070829 --> I want 2007-08-29
890829 --> 1989-08-29

ok, the 'function' 'sed' should be able to do it for you.

The sed string to do that is worse than writing a shell function to do it IMO -

#!/bin/ksh
format ()
{
        yr=`expr substr $1 1 2`      
        month=`expr substr $1 5 2`
        day=`expr substr $1 7 2`
        if [[ $yr > "30" ]] ; then
             echo "19""$yr-$month-$day"
        else
             echo "20"$yr-$month-$day"
        fi
}

new_date=$(format "041012")
echo $new_date

Edit per vgersh99 observation.

Jim,
that was not the desired input format.

given a sample input file 'mySampleFile.txt':

070829
890829
050829
sed 's/\([^0].\)\(..\)\(..\)/19\1-\2-\3/g;s/\(0.\)\(..\)\(..\)/20\1-\2-\3/g' mySampleFile.txt

Script will fail on where year is 90, 80, 70 and so on:

echo "801229" | sed 's/\([^0].\)\(..\)\(..\)/19\1-\2-\3/g;s/\(0.\)\(..\)\(..\)/20\1-\2-\3/g'
198200--12--29

I think it should be:

sed 's/\([^0].\)\(..\)\(..\)/19\1-\2-\3/g;s/^\(0.\)\(..\)\(..\)/20\1-\2-\3/g' mySampleFile.txt

Regards,
Tayyab

Thank you for your answers,

I manage it like that :

#!/bin/ksh
export a

format ()
{
yr=`expr substr $1 1 2`
month=`expr substr $1 5 2`
day=`expr substr $1 3 2`
if [[ $yr > "30" ]] ; then
echo "19""$yr-$month-$day"
else
echo "20""$yr-$month-$day"
fi
}

while read a
do
format $a >> TriDate.txt
done < $1

I have got another question , how can I remove the first line and the last line of a file ???

thank you thank you

Another question on the format() function

how does it come that the test :
[[ $yr > "30" ]]

works, but "30" is alphanumeric not numeric

I think tests on alphanumeric are : =, !=

and tests on numerics are : -eq, -ne, -gt, -ge, -lt, -le

?????????????????????????????????????

because yr can be 06, it's easier to use a string comparison. For me.