在使用perl進行指令碼開發時,不可避免地需要進行時間轉換,以下例子是將系統時間轉換為標準時間:
#!/usr/bin/perl
use strict;
use DBI;
$|=1;
my $username = "root" ;
my $password = "123456";
my $dbhost = "db-server";
my $dbport = "3306";
my $now = time();
my $date = time_2_local($now);
my $sql = "update tablename set DateTime='$date' where id='1340848776'";
print("sql is $sql\n");
if ($sql)
{
my $dbh;
my $dbh = DBI->connect("dbi:mysql:dbname:$dbhost:$dbport", $username, $password);
my $sth;
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->finish();
$dbh->disconnect(); #close the connection
}
die;
sub time_2_local
{
my $now = shift;
my ($seconds,$minute,$hour,$day,$month,$year) = localtime($now);
$year = $year+1900;
$month = $month+1;
if ($month < 10)
{
$month = "0".$month;
}
if ($day < 10)
{
$day = "0".$day;
}
if ($hour < 10)
{
$hour = "0".$hour;
}
if ($minute < 10)
{
$minute = "0".$minute;
}
if ($seconds < 10)
{
$seconds = "0".$seconds;
}
return "$year-$month-$day $hour:$minute:$seconds";
}
以下例子是標準時間轉系統時間:
#!/usr/bin/perl
use Class::Date qw(date localdate);
use strict;
$|=1;
my $unixtime = date("2012-07-06 14:48:54")->epoch;
print $unixtime ."\n";
$unixtime = date("2002-03-03 10:06");
print $unixtime ."\n";
die;
在使用perl進行指令碼開發時,不可避免地需要進行時間轉換,以下例子是將系統時間轉換為標準時間:
#!/usr/bin/perl
use strict;
use DBI;
$|=1;
my $username = "root" ;
my $password = "123456";
my $dbhost = "db-server";
my $dbport = "3306";
my $now = time();
my $date = time_2_local($now);
my $sql = "update tablename set DateTime='$date' where id='1340848776'";
print("sql is $sql\n");
if ($sql)
{
my $dbh;
my $dbh = DBI->connect("dbi:mysql:dbname:$dbhost:$dbport", $username, $password);
my $sth;
$sth = $dbh->prepare($sql);
$sth->execute();
$sth->finish();
$dbh->disconnect(); #close the connection
}
die;
sub time_2_local
{
my $now = shift;
my ($seconds,$minute,$hour,$day,$month,$year) = localtime($now);
$year = $year+1900;
$month = $month+1;
if ($month < 10)
{
$month = "0".$month;
}
if ($day < 10)
{
$day = "0".$day;
}
if ($hour < 10)
{
$hour = "0".$hour;
}
if ($minute < 10)
{
$minute = "0".$minute;
}
if ($seconds < 10)
{
$seconds = "0".$seconds;
}
return "$year-$month-$day $hour:$minute:$seconds";
}
以下例子是標準時間轉系統時間:
#!/usr/bin/perl
use Class::Date qw(date localdate);
use strict;
$|=1;
my $unixtime = date("2012-07-06 14:48:54")->epoch;
print $unixtime ."\n";
$unixtime = date("2002-03-03 10:06");
print $unixtime ."\n";
die;