Using DateTime

From ClassDBI

Jump to: navigation, search

The DateTime project is an attempt to produce the definitive way of handling dates and times in Perl. For more reasons, see Why Datetime?.

Using DateTime in Class::DBI is simple. Add the following to your base DB class:

 use DateTime;
 use DateTime::Format::Pg;
 # Allow a column to be exposed as a DateTime object simply.
 sub has_datetime {
     my $class = shift;
     my ( $field ) = @_;
     $class->has_a(
         $field => 'DateTime',
         inflate => sub { DateTime::Format::Pg->parse_datetime( shift ) },
         deflate => sub { DateTime::Format::Pg->format_datetime( shift ) },
     );
 }

Then, you can make a column automatically return DateTime objects in the defining class:

 __PACKAGE__->has_datetime( 'created_on' );

NB: The example assumes PostgreSQL, but there is an alternative module for MySQL.