转换字符串“20-May-07”到目前为止和操纵 [英] Convert string "20-May-07" to date and manipulate

查看:105
本文介绍了转换字符串“20-May-07”到目前为止和操纵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的perl程序中,我正在从保修期结束日期计算保修开始日期差额为3年。以下是我迄今为止写的代码块:

In my perl program, I am calculating warranty start date from warranty end date The difference is 3 years. Following is the chunk of code that I have written so far:

use Time::ParseDate;
use DateTime;
use POSIX;
use DateTime::Duration;

my $warranty_expiration_string = "20-May-07";
my $epoch = parsedate($warranty_expiration_string);
my $warranty_expiration = strftime "%D", localtime($epoch);   # returns: 05/20/07

如何从中扣除3年$ warranty_expiration 获取 $ warranty_start date?

我试过,

How do I deduct 3 years from $warranty_expiration to get $warranty_start date?
I tried,

$warranty_start->subtract(DateTime::Duration->new('years' => 3));

..但没有工作。

推荐答案

我不明白所有不同的日期/时间模块混合。你只需要一些,而不是全部。如果您想要使用 DateTime 进行日期数学计算,则需要这样:

I don't understand all the different date/time modules being mixed. You only need some of them, not all of them. If you want to do date math using DateTime anyway, you want something like this:

use DateTime;
use DateTime::Format::Strptime;

my $dateparser = DateTime::Format::Strptime->new( pattern => '%d-%b-%y' );

my $warranty_expiration = $dateparser->parse_datetime($warranty_expiration_string);
my $warranty_start      = $warranty_expiration->clone->subtract( years => 3);

大多数DateTime :: Format :: *模块都是与DateTime一起使用,我更喜欢使用那些,如果可以的话。

Most of the DateTime::Format::* modules are meant to be used with DateTime and I prefer to use those if I can.

您还可以在以下位置阅读有关正在进行的DateTime项目和推荐模块的更多信息:

You may also want to read more about the ongoing DateTime project and the list of recommended modules at:

  • http://datetime.perl.org

这篇关于转换字符串“20-May-07”到目前为止和操纵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆