Julian Date

I have a shell script which gets passed a parameter which is a combination of Year and Julian Date <YYYYj>. So April 11th, julian date is 101. So if I wanted April 11th for 2003 I would get the following value 2003101. How would I convert that in unix to be 20030411? I am using the korn shell.

Well if you can alter the script that's passing the parameter, you could change the piece of code, such as date +%Y%j, so that it sends what you want it to send, such as date +%Y%m%d.

Otherwise...
Assuming the variable that stores that passed value is called varPassed, you can put this (ksh) code in a file called someScript, make it executable, and call it with newValue=`someScript $varPassed`:

varPassed=$1

month=1
flag=0

theYear=`echo $varPassed | awk '{print substr ($0, 1, 4)'}`
dayOfYear=`echo $varPassed | awk '{print substr ($0, 5, 3)'}`
dayOfYear=`expr $dayOfYear - 0`

TestLeapYear() {
  if [[ `expr $theYear % 4` != 0 && $dayOfYear -gt 28 ]] then
    month=`expr $month + 1`
    dayOfYear=`expr $dayOfYear - 28`
  else
    if [[ `expr $theYear % 4` = 0 && $dayOfYear -gt 29 ]] then
      month=`expr $month + 1`
      dayOfYear=`expr $dayOfYear - 29`
    else
      flag=1
    fi
  fi
}

Days30() {
  if [[ $dayOfYear -gt 30 ]] then
    month=`expr $month + 1`
    dayOfYear=`expr $dayOfYear - 30`
  else
    flag=1
  fi
}

Days31() {
  if [[ $dayOfYear -gt 31 ]] then
    month=`expr $month + 1`
    dayOfYear=`expr $dayOfYear - 31`
  else
    flag=1
  fi
}

Days31 #january
if [[ $flag = 0 ]] then
  TestLeapYear #february
fi
if [[ $flag = 0 ]] then
  Days31 #march
fi
if [[ $flag = 0 ]] then
  Days30 #april
fi
if [[ $flag = 0 ]] then
  Days31 #may
fi
if [[ $flag = 0 ]] then
  Days30 #june
fi
if [[ $flag = 0 ]] then
  Days31 #july
fi
if [[ $flag = 0 ]] then
  Days31 #august
fi
if [[ $flag = 0 ]] then
  Days30 #september
fi
if [[ $flag = 0 ]] then
  Days31 #october
fi
if [[ $flag = 0 ]] then
  Days30 #november
fi

if [[ $month -lt 10 ]] then
  month=0$month
fi
if [[ $dayOfYear -lt 10 ]] then
  dayOfYear=0$dayOfYear
fi

echo $theYear$month$dayOfYear
1 Like

What you're doing is more of a day-of-year thing rather than a Julian number thing. But a Julian number calculator can handle this stuff easily.

Get the Julian number for the day before Jan 1 of the year in question:
datecalc -j 2002 12 31
52639

Now calculate the JD of the date you want:
52740=52639+101

Lastly, convert that to a date:
datecalc -j 52740
2003 4 11

Of course, you will want to read the output of the last command into some variables, not just display them.

With ksh, this is really just a one-liner:

Y=2003
DOY=101
datecalc -j $(($(datecalc -j $((Y-1)) 12 31) + DOY)) | read year month day

You can get datecalc here.

I see oombera beat me to the punch here 8) Oh well, now you have two options..

thanks for your help