Saturday, October 16, 2010

Time::Piece's Missing Part

Time::Piece is a great module. The only thing I really miss in it is a truncate method, similar to the one that DateTime has. Fortunately it is quite easy to add it to the original distribution.

I've written a monkey patch, but I look forward for this method in the future versions of Time::Piece.

#!/usr/bin/perl
use strict;
use warnings;

use Time::Piece;

local *Time::Piece::truncate;
*Time::Piece::truncate = sub {
    package Time::Piece;
    my ($time, $to) = @_;
    my @t = (0, 0, 0, 1, 0);
    return $time->_mktime([@t[0..$to-1], @$time[$to..c_isdst]], $time->[c_islocal]);
};

my $now = Time::Piece->gmtime;
my $midnight = $now->truncate(Time::Piece::c_mday);
print $midnight, "\n";

No comments: