1 |
3 |
ahitrov@rambler.ru |
package Contenido::DateTime; |
2 |
|
|
|
3 |
|
|
use strict; |
4 |
|
|
use warnings; |
5 |
|
|
|
6 |
|
|
use Contenido::Errors; |
7 |
|
|
use DateTime; |
8 |
|
|
use DateTime::Locale; |
9 |
|
|
use DateTime::Format::Pg; |
10 |
|
|
use DateTime::Format::Strptime; |
11 |
|
|
use Data::Dumper; |
12 |
|
|
|
13 |
|
|
{ |
14 |
|
|
BEGIN { |
15 |
|
|
$^W = 0; |
16 |
|
|
|
17 |
|
|
DateTime::Locale->register( |
18 |
|
|
id => 'ru_RU_KOI8_R', |
19 |
|
|
en_language => 'Russian', |
20 |
|
|
replace => 1, |
21 |
|
|
); |
22 |
|
|
} |
23 |
|
|
|
24 |
|
|
no warnings 'redefine'; |
25 |
|
|
*DateTime::Format::Pg::format_datetime = \&DateTime::Format::Pg::format_timestamp; |
26 |
|
|
} |
27 |
|
|
|
28 |
|
|
sub new { |
29 |
|
|
shift if $_[0] and $_[0] eq __PACKAGE__; |
30 |
|
|
|
31 |
|
|
my ($key, $value) = @_; |
32 |
|
|
my ($dt, $no_timezone, $no_locale, $no_formatter); |
33 |
|
|
my $formatter = DateTime::Format::Pg->new(); |
34 |
|
|
|
35 |
|
|
if ($key) { |
36 |
|
|
return unless $value; |
37 |
|
|
for ($key) { |
38 |
|
|
/postgres/ && do { |
39 |
|
|
last unless ref $value eq ""; |
40 |
|
|
eval { $dt = $formatter->parse_datetime($value) }; |
41 |
|
|
last; |
42 |
|
|
}; |
43 |
|
|
/epoch/ && do { |
44 |
|
|
last unless ref $value eq ""; |
45 |
|
|
eval { $dt = DateTime->from_epoch(epoch => $value) }; |
46 |
|
|
last; |
47 |
|
|
}; |
48 |
|
|
/strptime/ && do { |
49 |
|
|
last unless ref $value eq "HASH"; |
50 |
|
|
$no_timezone = 1 if $value->{"time_zone"}; |
51 |
|
|
$no_locale = 1 if $value->{"locale"}; |
52 |
|
|
|
53 |
|
|
my $strptime = DateTime::Format::Strptime->new( |
54 |
|
|
pattern => $value->{"format"}, |
55 |
|
|
locale => $value->{"locale"} || "ru_RU_KOI8_R", |
56 |
|
|
time_zone => $value->{"time_zone"} || "Europe/Moscow", |
57 |
|
|
diagnostic => 0, |
58 |
|
|
); |
59 |
|
|
|
60 |
|
|
eval { $dt = $strptime->parse_datetime($value->{"datetime"}) }; |
61 |
|
|
last; |
62 |
|
|
}; |
63 |
|
|
/datetime/ && do { |
64 |
|
|
last unless ref $value eq "HASH"; |
65 |
|
|
$no_formatter = 1 if $value->{"formatter"}; |
66 |
|
|
$no_timezone = 1 if $value->{"time_zone"}; |
67 |
|
|
$no_locale = 1 if $value->{"locale"}; |
68 |
|
|
eval { $dt = DateTime->new(%{$value}) }; |
69 |
|
|
last; |
70 |
|
|
}; |
71 |
|
|
} |
72 |
|
|
|
73 |
|
|
return unless $dt; |
74 |
|
|
} else { |
75 |
|
|
$dt = DateTime->now(); |
76 |
|
|
} |
77 |
|
|
|
78 |
|
|
$dt->set_locale("ru_RU_KOI8_R") unless $no_locale; |
79 |
|
|
$dt->set_time_zone("Europe/Moscow") unless $no_timezone; |
80 |
|
|
$dt->set_formatter($formatter) unless $no_formatter; |
81 |
|
|
|
82 |
|
|
return $dt; |
83 |
|
|
} |
84 |
|
|
|
85 |
|
|
1; |