[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Omaha.pm] Class::Date makes life cleaner




Before Class::Date we used a DateConvert() method we wrote where you had to remember arbitrary conversions like "25" and "2" and "18" and remember what those meant, writing code like this:

  my $arrival_date = $Folio->get_arrival;
  $arrival_date = $Folio->DateConvert($arrival_date, 25);
  my $arrival_time = $Folio->DateConvert($arrival_date, 2);
  $arrival_date = $Folio->DateConvert($arrival_date, 18);
  $arrival_date = $Folio->DateConvert($arrival_date, 13);
  $R_Folio->set_arrival_date($arrival_date);
  $arrival_time = substr($arrival_time, 0, 5);
  $arrival_time =~ s/\:+//;
  $R_Folio->set_arrival_time($arrival_time);
  my $depart_date = $Folio->get_departure;
  $depart_date = $Folio->DateConvert($depart_date, 25);
  my $depart_time = $Folio->DateConvert($depart_date, 2);
  $depart_date = $Folio->DateConvert($depart_date, 18);
  $depart_date = $Folio->DateConvert($depart_date, 13);
  $R_Folio->set_departure_date($depart_date);
  $depart_time = substr($depart_time, 0, 5);
  $depart_time =~ s/\:+//;
  $R_Folio->set_departure_time($depart_time);
  # ...
  my $nights = ($depart_date - $arrival_date);
  $R_Folio->set_number_of_stay_nights($nights);

Thanks to Class::Date we can write code like this (our Class::Date wrapper is called Control::DateTime):

 $R_Folio->set_arrival_depart($Folio->get_arrival, $Folio->get_departure);

 sub set_arrival_depart {
   my ($self, $arrival, $depart) = @_;
   my $arrival   = Control::DateTime->new($arrival);
   my $departure = Control::DateTime->new($depart);

   $self->set_arrival_date($arrival->format("%Y%m%d"));
   $self->set_arrival_time($arrival->format("%H%M"));

   $self->set_departure_date($departure->format("%Y%m%d"));
   $self->set_departure_time($departure->format("%H%M"));

   $self->set_number_of_stay_nights(
     ($departure - $arrival)->day
   );
   return 1;
 };

Yay!

%Y = 4 digit year
is a lot easier to remember and read than

 25 converts 'Sep 02 2003 12:00AM' to 'yyyy-mm-ddThh:00:00'

Here's to progress,  -grin-

j
perl -e '$_ = "jwh"; s/w/ap/; print;'