【问题标题】:PERL : I take mday value from locatime as below , . How can I subtract 1 from mday which I take from localtimePERL:我从 locatime 中获取 mday 值,如下所示。如何从本地时间获取的 mday 中减去 1
【发布时间】:2020-10-13 17:36:32
【问题描述】:

PERL:我从 locatime 获取 mday 值如下,现在我想要前天的值。如何从本地时间获取的 mday 中减去 1

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();
my $part = "P".$mday;

print "Today value is $part \n";

my $part_yes = "P".$mday - $num;

print "$part_yes \n";

【问题讨论】:

  • 我的 ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime();我的 $part = "P".$mday; print "今天的价值是 $part \n";我的 $part_yes = "P".$mday - $num;打印 "$part_yes \n";
  • 如果您只需要$mday,请忽略其他值:my $mday = ( localtime )[3];
  • 在一个地方,您说要提前 2 天。在另一个地方,你说你想要提前一天。是哪个?

标签: perl date time timezone nls


【解决方案1】:

使用日期时间:

my $dt =
   DateTime
   ->now( time_zone => 'local' )
   ->set_time_zone('floating')  # Do this when working with dates.
   ->truncate( to => 'days' );  # Optional.

$dt->subtract( days => 2 );

my $yesterday = $dt->day;

DateTime 相当繁重,似乎人们问日期时间问题总是会说“只使用核心模块!”,所以这里有一个只使用核心模块的解决方案。

use Time::Local qw( timegm );

# Create an timestamp with the same date in UTC as the one local one.
my $epoch = timegm(0, 0, 0, ( localtime() )[3,4,5]);

# We can now do date arithmetic without having to worry about DST switches.
$epoch -= 2 * 24*60*60;

my $yesterday = ( gmtime($epoch) )[3] + 1;

【讨论】:

    【解决方案2】:
    my $now = time(); # time as seconds since 1970-01-01
    my $day_ago = $now - 24*60*60;
    
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($day_ago);
    my $part = "P".$mday;
    

    警告(ikegami 评论):并非所有日子都有 24 小时。这可能会产生提前 0、1 或 2 天的结果

    https://perldoc.perl.org/functions/time
    https://perldoc.perl.org/functions/localtime

    【讨论】:

    • “前天”应该是2*24*60*60
    • 并非所有日子都有 24 小时。这可能会产生提前 0、1 或 2 天的结果
    • @ikegami 我添加了夏令时警告。简单且无模块的配方可能在许多但不是所有情况下都有用。
    • 我想不出在哪一种情况下它是有用的,所以说它在很多情况下都有用可能有点夸大其词。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2018-12-09
    • 1970-01-01
    相关资源
    最近更新 更多