#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Time::Local;
sub timestamp2date {
my $timestamp = shift;
my ($sec, $min, $hour, $day, $mon, $year) = localtime($timestamp);
return sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year + 1900, $mon + 1, $day, $hour, $min, $sec);
}
sub date2timestamp {
my $date = shift;
my ($year, $mon, $day, $hour, $min, $sec) = ($date =~ /(\d{4})\-([01]\d)\-([0-3]\d) ([0-2]\d):([0-5]\d):([0-5]\d)/);
return timelocal($sec, $min, $hour, $day, $mon - 1, $year);
}
my ($sec, $min, $hour, $day, $mon, $year) = localtime(time);
my $now = sprintf('%04d-%02d-%02d %02d:%02d:%02d', $year + 1900, $mon + 1, $day, $hour, $min, $sec);
my $timestamp = &date2timestamp($now);
my $date = ×tamp2date($timestamp);
print "Change date format to timestamp.\n";
print "Now: $now\n";
print "Timestamp: $timestamp\n";
print "Date: $date\n\n";
sleep 5;
my $current_timestamp = time;
$date = ×tamp2date($current_timestamp);
$timestamp = &date2timestamp($date);
print "Change timestamp to date format.\n";
print "Timestamp: $current_timestamp\n";
print "Date: $date\n";
print "Date to Timestamp: $timestamp\n";
実行結果
Change date format to timestamp.
Now: 2010-10-28 17:28:42
Timestamp: 1288254522
Date: 2010-10-28 17:28:42
Change timestamp to date format.
Timestamp: 1288254527
Date: 2010-10-28 17:28:47
Date to Timestamp: 1288254527