I have a script which renders timestamps in the format YYYY'DDD'TTT where Y = year, D = day out of 365 and T = time in 1000th's of the day:

s=$(($(date +"%H*3600+%M*60+%S")))
t=$(($s * 5 / 432))
d=$(date +%j)
y=$(date +%Y)
printf "$y\`$d\`$t" "$y" "$d" "$t"

but I need to modify it so that D and T will always produce a three-character value (ie, '001' instead of '1' for Jan 1, '001' instead of '1' for the first minute of the day) - and I have no idea how.

Any help is hugely appreciated


Perhaps you could take a look at the printf format string. The first parameter of printf should be a format string which includes placeholders for each of the arguments that follow.

You can include %d to represent an argument in signed decimal format, and you can prefix d by 0n for n characters of zero padding.

printf "%d/%d/%d" 2011 2 3

Will output 2011/2/3

printf "%04d/%03d/%05d" 2011 2 45

Should output 2011/002/00045

  • Thanks! That does help, but my real problem is that I can't just insert additional zeros, since after the first 99 values (days, ect), the value gains a third character on it's own. My script needs to pad values < 100 with one zero, and values < 10 with two zeros, if that makes sense... – Jack Anders Sep 29 '11 at 15:19
  • 1
    That is what the printf "%03d" is doing. The '3' is 'minimum' width and the '0' means to pad with a zero character ('0') to fill the minimum width. See the examples that digitalsean gave. Notice that the "2011" did not have any zeros added, because it met the minimum width. – Arcege Sep 29 '11 at 16:15

Let date do the work!

date +%3j

Then, for the milliday part, a simple trick is to compute 1000 plus the number of millidays and strip away the leading 1. So for your script:

s=$(($(date +"%H*3600+%M*60+%S")))
t=$(($s * 5 / 432 + 1000))
date "+%Y'%3j'${t#1}"
  • For using date alone, +1, but as shown, 2011-01-01 00:02 produces 2011'001'1 without the zero-padding .... Here is a tweaked variant: t=00$(($(($(date +"%H*3600+%M*60+%S"))) * 5 / 432)); date "+%Y'%3j'${t:(-3)}" – Peter.O Sep 30 '11 at 3:35
  • @fred Oops, good spot. I've edited to a more portable way of padding the number. – Gilles 'SO- stop being evil' Sep 30 '11 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.