perl 字符串转换为日期

现在有这样的需求:命令行参数接收如‘20140225’这样的字符串参数,我怎样取出它的前一天、后一天?localtime能实现吗?

用Date::Calc包可以实现。

 方法清单:

      Days_in_Year
      Days_in_Month
      Weeks_in_Year
      leap_year
      check_date
      check_time
      check_business_date
      Day_of_Year
      Date_to_Days
      Day_of_Week
      Week_Number
      Week_of_Year
      Monday_of_Week
      Nth_Weekday_of_Month_Year
      Standard_to_Business
      Business_to_Standard
      Delta_Days
      Delta_DHMS
      Delta_YMD
      Delta_YMDHMS
      N_Delta_YMD
      N_Delta_YMDHMS
      Normalize_DHMS
      Add_Delta_Days
      Add_Delta_DHMS
      Add_Delta_YM
      Add_Delta_YMD
      Add_Delta_YMDHMS
      Add_N_Delta_YMD
      Add_N_Delta_YMDHMS
      System_Clock
      Today
      Now
      Today_and_Now
      This_Year
      Gmtime
      Localtime
      Mktime
      Timezone
      Date_to_Time
      Time_to_Date
      Easter_Sunday
      Decode_Month
      Decode_Day_of_Week
      Decode_Language
      Decode_Date_EU
      Decode_Date_US
      Fixed_Window
      Moving_Window
      Compress
      Uncompress
      check_compressed
      Compressed_to_Text
      Date_to_Text
      Date_to_Text_Long
      English_Ordinal
      Calendar
      Month_to_Text
      Day_of_Week_to_Text
      Day_of_Week_Abbreviation
      Language_to_Text
      Language
      Languages
      Decode_Date_EU2
      Decode_Date_US2
      Parse_Date
      ISO_LC
      ISO_UC



 其中,

Add_Delta_Days
    =>

 ($year,$month,$day) =
     Add_Delta_Days($year,$month,$day,  $Dd);

这个方法应该能够满足要求

追问

Add_Delta_Days($year,$month,$day, $Dd)中的$Dd代表什么?能举个例子吗?具体怎么用?多谢!

追答

$Dd就是日期偏移量呗,前一天就用-1,后一天就用1

#!/usr/bin/perl
use strict;
use Date::Calc qw(Date_to_Time Time_to_Date Add_Delta_Days);

my $dt='20140225';
my $y=substr($dt, 0, 4);
my $m=substr($dt,4,2);
my $d=substr($dt,6,2);


print "今天是 $dt\n"; 
my ($y1, $m1, $d1) = Add_Delta_Days($y + 0, $m + 0, $d + 0,-1);
print "昨天是 ", $y1 * 10000 + $m1 * 100 + $d1 , "\n";
my ($y2, $m2, $d2) = Add_Delta_Days($y + 0, $m + 0, $d + 0, 1);
print "明天是 " , $y2 * 10000 + $m2 * 100 + $d2 , "\n";

温馨提示:答案为网友推荐,仅供参考