如何在Perl中获取昨天的日期? [英] How do I get yesterday's date in perl?

查看:45
本文介绍了如何在Perl中获取昨天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我使用以下日期获取今天的日期.我需要使用此日期获取昨天的日期..我怎么能得到那个?

Currently i take today date using below.I need to get yesterday date using this.. how can i get that ?

my $today = `date "+%Y-%m-%d"`;

推荐答案

如果要昨天的日期:

use DateTime qw( );

my $yday_date =
   DateTime
      ->now( time_zone => 'local' )
      ->set_time_zone('floating')
      ->truncate( to => 'day' )
      ->subtract( days => 1 )
      ->strftime('%Y-%m-%d');

例如,在纽约,2019年5月14日的01:00:00,它将返回2019年5月13日.

For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13.

例如,在纽约,2019年11月4日00:00:00,它将返回2019年11月3日.

For example, in New York on 2019-11-04 at 00:00:00, it would have returned 2019-11-03.

请注意,使用的是-> now(time_zone =>'local')-> set_time_zone('floating')-> truncate(to =>'day')以避免此问题.

Note that ->now( time_zone => 'local' )->set_time_zone('floating')->truncate( to => 'day' ) is used instead of ->today( time_zone => 'local' ) to avoid this problem.

如果您想提前一天的时间:

If you want the time a day earlier:

use DateTime qw( );

my $yday_datetime =
   DateTime
      ->now( time_zone => 'local' )
      ->subtract( days => 1 )
      ->strftime('%Y-%m-%d %H:%M:%S');

例如,在纽约,2019年5月14日的01:00:00,它将返回2019-05-13 01:00:00.

For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13 01:00:00.

例如,在纽约,2019年3月10日的12:00:00,它将返回2019-03-09 12:00:00.

For example, in New York on 2019-03-10 at 12:00:00, it would have returned 2019-03-09 12:00:00.

例如,在纽约,2019-03-11 02:30:00,它将导致错误.2019-03-10 02:30:00因为切换到夏时制,所以不存在.

For example, in New York on 2019-03-11 at 02:30:00, it would have resulted in an error. 2019-03-10 02:30:00 didn't exist because of the switch to Daylight Saving Time.

如果您希望时间早24小时:

If you want the time 24 hours earlier:

use DateTime qw( );

my $yday_datetime =
   DateTime
      ->now( time_zone => 'local' )
      ->subtract( hours => 24 )
      ->strftime('%Y-%m-%d %H:%M:%S');

例如,在纽约,2019年5月14日的01:00:00,它将返回2019-05-13 01:00:00.

For example, in New York on 2019-05-14 at 01:00:00, it would have returned 2019-05-13 01:00:00.

例如,在纽约,2019年3月10日的12:00:00,它将返回2019-03-09 11:00:00.

For example, in New York on 2019-03-10 at 12:00:00, it would have returned 2019-03-09 11:00:00.

例如,在纽约,2019-03-11 02:30:00,它将返回2019-03-10 01:30:00.

For example, in New York on 2019-03-11 at 02:30:00, it would have returned 2019-03-10 01:30:00.

这篇关于如何在Perl中获取昨天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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