The time_zone function in DateTime::Format::Strptime is only called with
parse_datetime.  I think a nice feature would be to also set the time_zone
when calling format_datetime.

I have my own subclass which does this now, but find myself using this more
and more in a lot of different projects.  I thought it may be useful to have
this same functionality in the main module.

Here's why:

I store dates and datetimes in UTC.  I do all date math, queries, sorting,
etc, using UTC.  All uses are associated with a time_zone.  When a user logs
in their time_zone is pulled and any display that has a datetime is
formatted so it reflects their timezone setting.

Basically I have a subclass of DateTime::Format::Strptime that takes one
more parameter; a boolean that if true will format the datetime object with
what is returned from time_zone.

Example:

use strict;
use DateTime;

my $datetime = DateTime->now; # Defaults to UTC

my $format_string = '%m/%d/%Y %T';
my $user_timezone = 'America/New_York';

my $Strp = new My::DateTime::Format::Strptime(
     pattern => $format_string,
     time_zone => $user_timezone,
     format_with_time_zone => 1,
);

print $Strp->format_datetime($datetime); # Converts from UTC to the User's
time_zone


package My::DateTime::Format::Strptime;

use base 'DateTime::Format::Strptime';


sub new {
    my $class = shift;
    my %args = @_;

    my $format_with_time_zone = delete $args{format_with_time_zone};

    my $self = $class->SUPER::new(%args);

    $self->{__format_with_time_zone} = $format_with_time_zone;

    bless $self, $class;
}

sub format_datetime {
    my ( $self, $dt ) = @_;
    my $format_me = $self->{__format_with_time_zone} ?
$dt->clone->set_time_zone($self->time_zone) : $dt;
    $self->SUPER::format_datetime($format_me);
}

1;



Thanks,
Kevin

Reply via email to