Debian Codegraph @

lib/XML/Feed/Util.pm

raw
1 package XML::Feed::Util;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.0.1';
6
7 use base qw( Exporter );
8 use DateTime::Format::Flexible;
9 use DateTime::Format::ISO8601;
10 use DateTime::Format::Natural;
11 use DateTime::Format::W3CDTF;
12 use DateTime::Format::Mail;
13
14 our @EXPORT_OK = qw(
15 format_w3cdtf
16 parse_datetime
17 parse_w3cdtf_date
18 parse_mail_date
19 );
20
21 sub format_w3cdtf {
22 my $dt = shift;
23
24 my $date = DateTime::Format::W3CDTF->format_datetime($dt);
25
26 # Add timezone "Z" if "floating" DateTime.
27 $date .= 'Z' if $dt->time_zone->is_floating;
28
29 return $date;
30 }
31
32 sub parse_datetime {
33 my $ts = shift or return undef;
34
35 $ts = _strip_spaces($ts);
36
37 return eval { DateTime::Format::ISO8601->parse_datetime($ts) }
38 || eval { DateTime::Format::Flexible->parse_datetime($ts) }
39 || do {
40 my $p = DateTime::Format::Natural->new;
41 my $dt = $p->parse_datetime($ts);
42 $p->success ? $dt : undef;
43 };
44 };
45
46 sub parse_mail_date {
47 my $ts = shift or return undef;
48
49 $ts = _strip_spaces($ts);
50
51 return eval { DateTime::Format::Mail->new(loose => 1)->parse_datetime($ts) }
52 || parse_datetime($ts);
53 };
54
55 sub parse_w3cdtf_date {
56 my $ts = shift or return undef;
57
58 $ts = _strip_spaces($ts);
59
60 return eval { DateTime::Format::W3CDTF->parse_datetime($ts) }
61 || parse_datetime($ts);
62 };
63
64 sub _strip_spaces {
65 local $_ = shift;
66 s/^\s+//, s/\s+$// if $_;
67 return $_;
68 }
69
70 1;
71
72 __END__
73
74 =head1 NAME
75
76 XML::Feed::Util - Utility functions
77
78 =head1 SYNOPSIS
79
80 use XML::Feed::Util qw(
81 format_w3cdtf
82 parse_datetime
83 parse_mail_date
84 parse_w3cdtf_date
85 );
86 use DateTime;
87
88 print format_w3cdtf(DateTime->now);
89
90 my $dt;
91 $dt = parse_datetime('January 8, 1999');
92 $dt = parse_mail_date('Fri, 23 Nov 2001 21:57:24 -0600');
93 $dt = parse_w3cdtf_date('2003-02-15T13:50:05-05:00');
94
95 =head1 DESCRIPTION
96
97 Common utility or helper functions.
98
99 =head1 USAGE
100
101 =head2 format_w3cdtf($datetime)
102
103 Convert DateTime object to W3CDTF format string.
104 Uses default timezone "Z" for "floating" DateTime.
105
106 =head2 parse_datetime($date)
107
108 Parse any date string using L<DateTime::Format::ISO8601>,
109 L<DateTime::Format::Flexible> or L<DateTime::Format::Natural>.
110
111 Returns DateTime object or undef.
112
113 =head2 parse_mail_date($date)
114
115 Parse date in RFC2822/822 format using L<DateTime::Format::Mail>.
116 Fallback to C<parse_datetime()> for other formats.
117
118 Returns DateTime object or undef.
119
120 =head2 parse_w3cdtf_date($date)
121
122 Parse date W3CDTF format using L<DateTime::Format::W3CDTF>.
123 Fallback to C<parse_datetime()> for other formats.
124
125 Returns DateTime object or undef.
126
127 =head1 AUTHOR & COPYRIGHT
128
129 Please see the I<XML::Feed> manpage for author, copyright, and license
130 information.
131
132 =cut