convert date variable to doy variable

Hello:

I have a script that requires the use of DOY (as a variable) instead of YY/MM/DD. I already obtained these parameters from downloaded files and stored them as variables (i.e. $day, $month, $year).

Is there any simple script that I could incorporate in mine to do this job?

Regards,

Antonio

date '+%j'

To convert a string to date and output the "Julian" date use the following:

 # date -d "2008-01-02" +%j
002

This is assuming your using GNU date.

Just one more question. I was able to get the DOY. I included it in my script by making the following:

$comm = "date -d $year-$month-$day +%j";
system("$comm");

For 2008/12/16 the scripts prints in the screen 351.

However, at the end of the day I need to capture the answer, 351 for instance, as a variable. I am sorry but I am new at linux.

Regards,

Shell:

DOY=`date -d $year-$month-$day +%j`

Perl:

$DOY=`date -d $year-$month-$day +%j`;

Is this a Perl script? Sounds like it if you are using the system command.

$ cat ./date_test.pl
#!/usr/bin/perl

use strict;
use warnings;
use POSIX qw(strftime);
use Time::Local;

#If you just want the julian of the current system date
my $x;

$x = strftime("%j", localtime());

print "x = $x\n";

#If you want the julian of a specific date, let's say 2008-12-10
my $testdate;
my $yyyy = 2008;
my $mm   = 12;
my $dd   = 10;

$testdate = timelocal(0, 0, 0, $dd, $mm-1, $yyyy);
$x = strftime("%j", localtime($testdate));
print "x = $x\n";

exit 0;


$ ./date_test.pl
x = 351
x = 345

$ date -d "2008-12-16" +%j
351

$ date -d "2008-12-10" +%j
345

If you are using ksh93, support for date calculations and conversions is built in.

$ doy=$(printf "%(%j)T" "2008-12-16")
$ print $doy
351
$ doy=$(printf "%(%j)T")
$ print $doy
352
$

Thank you very much for all your help. I finally used the following script which seems to work:

open(DATE, "date -d $year-$month-$day +%j|");
$DOY = <DATE>;
close(DATE);
print %DOY

If this is a Perl script, and it looks like it is, I wouldn't recommend getting the date from the OS. Use Perl's built-in date functions if you are going to use Perl. It's more efficient and more portable. If you are going to call the OS for a simple thing like a date, then you might as well just use a shell script.

Perl Date FAQs
perlfaq4

There are also Date modules you can download from CPAN that will make your life alot easier.