| 1 |
package Plagger::Date; |
|---|
| 2 |
use strict; |
|---|
| 3 |
use base qw( DateTime ); |
|---|
| 4 |
|
|---|
| 5 |
use Encode; |
|---|
| 6 |
use DateTime::Format::Strptime; |
|---|
| 7 |
use UNIVERSAL::require; |
|---|
| 8 |
|
|---|
| 9 |
sub rebless { bless $_[1], $_[0] } |
|---|
| 10 |
|
|---|
| 11 |
sub parse { |
|---|
| 12 |
my($class, $format, $date) = @_; |
|---|
| 13 |
|
|---|
| 14 |
my $module; |
|---|
| 15 |
if (ref $format) { |
|---|
| 16 |
$module = $format; |
|---|
| 17 |
} else { |
|---|
| 18 |
$module = "DateTime::Format::$format"; |
|---|
| 19 |
$module->require or die $@; |
|---|
| 20 |
} |
|---|
| 21 |
|
|---|
| 22 |
my $dt = $module->parse_datetime($date) or return; |
|---|
| 23 |
|
|---|
| 24 |
|
|---|
| 25 |
unless ($dt->time_zone->is_floating) { |
|---|
| 26 |
$dt->set_time_zone( Plagger->context->conf->{timezone} || 'local' ); |
|---|
| 27 |
} |
|---|
| 28 |
|
|---|
| 29 |
bless $dt, $class; |
|---|
| 30 |
} |
|---|
| 31 |
|
|---|
| 32 |
sub parse_dwim { |
|---|
| 33 |
my($class, $str) = @_; |
|---|
| 34 |
|
|---|
| 35 |
require Date::Parse; |
|---|
| 36 |
my $time = Date::Parse::str2time($str) or return; |
|---|
| 37 |
|
|---|
| 38 |
$class->from_epoch($time); |
|---|
| 39 |
} |
|---|
| 40 |
|
|---|
| 41 |
sub strptime { |
|---|
| 42 |
my($class, $pattern, $date) = @_; |
|---|
| 43 |
Encode::_utf8_on($pattern); |
|---|
| 44 |
my $format = DateTime::Format::Strptime->new(pattern => $pattern); |
|---|
| 45 |
$class->parse($format, $date); |
|---|
| 46 |
} |
|---|
| 47 |
|
|---|
| 48 |
sub now { |
|---|
| 49 |
my($class, %opt) = @_; |
|---|
| 50 |
my $self = $class->SUPER::now(); |
|---|
| 51 |
|
|---|
| 52 |
my $tz = $opt{timezone} || Plagger->context->conf->{timezone} || 'local'; |
|---|
| 53 |
$self->set_time_zone($tz); |
|---|
| 54 |
|
|---|
| 55 |
$self; |
|---|
| 56 |
} |
|---|
| 57 |
|
|---|
| 58 |
sub from_epoch { |
|---|
| 59 |
my $class = shift; |
|---|
| 60 |
my %p = @_ == 1 ? (epoch => $_[0]) : @_; |
|---|
| 61 |
|
|---|
| 62 |
$p{time_zone} = Plagger->context->conf->{timezone} || 'local'; |
|---|
| 63 |
$class->SUPER::from_epoch(%p); |
|---|
| 64 |
} |
|---|
| 65 |
|
|---|
| 66 |
sub format { |
|---|
| 67 |
my($self, $format) = @_; |
|---|
| 68 |
my $module = "DateTime::Format::$format"; |
|---|
| 69 |
$module->require or die $@; |
|---|
| 70 |
|
|---|
| 71 |
$module->format_datetime($self); |
|---|
| 72 |
} |
|---|
| 73 |
|
|---|
| 74 |
1; |
|---|