计算时间差(date和perl实现)

前端之家收集整理的这篇文章主要介绍了计算时间差(date和perl实现)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


#!/bin/bash

current_sec=`date +%s`

get_time=$1

get_time_sec=`date -d "$1" +%s`

sec_diff=$((current_sec - get_time_sec))
echo "Second difference is $sec_diff"

day_diff=$((sec_diff / 86400))
echo "Day difference is $day_diff"


#==================================== 
#    timediff usage: &timediff($date,$offset)
#    $date form : yyyymmdd
#    $offset form : [+-]daynum
#==================================== 
use Time::Local;
my $date = "20111210";
my $offset = '-20';
#my $offset = '+20';

sub timediff{
	my ($date,$offset) = @_;
	my $year_before = substr($date,4);
	my $mon_before = substr($date,4,2);
	my $day_before = substr($date,6,2);

	my $before = timelocal(undef,undef,$day_before,$mon_before-1,$year_before);

	my $after;
	if (substr($offset,1) eq "+")
	{
		$after = $before + substr($offset,1) * SECS_PER_DAY; 
	}
	elsif (substr($offset,1) eq "-")
	{
		$after = $before - substr($offset,1) * SECS_PER_DAY; 
	}
	else
	{
		die "Invalid offset!\n";
	}
	my ($sec,$min,$hour,$mday,$mon,$year) = localtime($after);
	$year += 1900;
	$mon += 1;
	return "$year$mon$mday\n";

}

print &timediff($date,$offset);




猜你在找的Perl相关文章