date_change
The filter converts dates and times,
formatted as follows:
|
MM[/-]DD[/-]YY(YY)?(:hh(mm)?)?
|
or:
|
YYYY[/-]MM[/-]DD(:hh(mm)?)?
|
into the following format:
If the year specification contains only two digits,
and is less than 50,
then it is treated as an offset from the year 2000,
and not from 1900.
In other words, 07 is understood as year 2007,
and 80 is understood as year 1980.
If no time is specified in the input then no time will be output.
The filter accepts three optional parameters, as follows:
- iso - Output date in ISO format.
- undef - Don't default to current date if no date is specified.
- no_time - Only output the date.
Ignore the time, if provided.
Example
- [filter date_change]2007-01-01[/filter]
- [filter date_change]2007/01/01[/filter]
- [filter date_change]2007-01-01:10[/filter]
- [filter date_change]2007/01/29:1536[/filter]
- [filter date_change]01-29-2007:1536[/filter]
- [filter date_change]01-29-07:1536[/filter]
- [filter date_change]01-29-68:1536[/filter]
|
Results in:
- 20070101
- 20070101
- 200701010010
- 200701291536
- 200701291536
- 200701291536
- 196801291536
|
Source code
sub {
my $val = shift;
shift;
my $opt = { map { $_ => 1 } @_ };
HTML::Entities::decode_entities($val) if $val =~ /&/;
$val =~ s/\0+//g;
my $re = $opt->{undef}
? qr:^(\d*)[-/]+(\d*)[-/]+(\d*)(.*)$:
: qr:^(\d+)[-/]+(\d+)[-/]+(\d+)(.*)$:
;
return $val unless $val =~ /$re/;
my ($year, $month, $day, $timeval);
if (length($1) == 4) {
($year, $month, $day) = ($1, $2, $3);
}
else {
($year, $month, $day) = ($3, $1, $2);
}
$timeval = $4;
if ($opt->{undef}) {
return unless grep /[1-9]/, ($year, $month, $day);
}
if (length($year) < 4) {
$year = $year < 50 ? $year + 2000 : $year + 1900;
}
my ($date_format, $time_format);
if ($opt->{iso}) {
$date_format = '%04d-%02d-%02d';
$time_format = 'T%02d:%02d:%02d';
}
else {
$date_format = '%04d%02d%02d';
$time_format = '%02d%02d';
}
my $time;
if ($timeval =~ /^:(\d{1,4})\s*$/) {
$time = sprintf('%04d', $1);
$time = sprintf($time_format, substr($time, 0, 2), substr($time, 2, 2));
}
elsif (
my ($hours, $minutes, $seconds) = ($timeval =~ /\s(\d\d?):(\d\d?)(?::(\d\d+))/)
) {
$time = sprintf($time_format, $hours, $minutes, $seconds);
}
my $out = sprintf($date_format, $year, $month, $day);
$out .= $time if $time and not $opt->{no_time};
return $out;
}
|