Doing this properly from ls is awkward because the date format changes with the age of the files. Furthermore, the computation for $M is suspect since ls normally returns a name for the month rather than a number. Presumably OP is using the date command to attempt to work around the differences in ls date format, but that means that all of the files would get the same value for a year.
However, OP's question is focused on leading zeros. That part is easy in awk:
D=$(ls -ltr $line | awk '{printf "%02d", $7}')
M=$(ls -ltr $line | awk '{printf "%02d", $6}')
Y=$(date +"%Y")
If I had to do this on HPUX, I would look into using Perl (which is preinstalled), since that can avoid the problems with ls and date format.
Here is a quick example (man perlfunc is where to start):
#!/usr/bin/perl -w
use strict;
for my $n ( 0 .. $#ARGV ) {
my (
$dev, $ino, $mode, $nlink, $uid, $gid, $rdev,
$size, $atime, $mtime, $ctime, $blksize, $blocks
) = stat( $ARGV[$n] );
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) =
localtime($mtime);
# printf "%s:", $ARGV[$n];
printf "%04d%02d%02d", 1900 + $year, 1 + $mon, $mday;
# printf "\n";
}
1;
I checked the script with the two printf statements uncommented, and looking at sample files. You would call this script with just one filename (for multiple filenames, the lack of formatting would be a nuisance).