为什么perl的本地时间似乎输出错误的月份? [英] Why does perl's localtime seem to output the wrong month?

查看:121
本文介绍了为什么perl的本地时间似乎输出错误的月份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到其他答案,但是由于某些原因他们并不适合我。

I've seen other answers, but they're not working for me for some reason.

我试图用Perl脚本中的日期以下代码。

I'm trying to get yesterday's date in a Perl script using the following code.

为了将来参考,今天的日期是2015年11月12日

For future reference, today's date is November 12, 2015

my (undef, undef, undef, $mday,$mon,$year) = localtime();
my $prev_day = timelocal(0, 0, 0, $mday-1, $mon, $year);
(undef, undef, undef, $mday,$mon,$year) = localtime($prev_day);
$year += 1900;

print "Yesterday's Day: $mday, Month: $mon, Year: $year\n";

除了我的输出看起来像这样

Except my output looks like this

Yesterday's Day: 11, Month: 10, Year: 2015.

我应该阅读昨天的日期为 Day:11,Month:11,Year:2015 。为什么要扣除这个月份?

I should be reading yesterday's date as Day: 11, Month: 11, Year: 2015. Why is the month being subtracted?

编辑:这不同于建议的答案,因为我想知道为什么当地时间似乎写错了一个月。 >

This is different than the suggested answer because I'm wondering why local time seems to be writing the wrong month.

推荐答案

localtime 的文档说这个

The documentation for localtime says this


$ mday是月份和月份月份在0..11范围内,0表示1月和11表示12月。

$mday is the day of the month and $mon the month in the range 0..11, with 0 indicating January and 11 indicating December.

所以要得到一个月的数字为1,您需要 $ mon + 1 ,或者您只需将一个添加到 $ mday 在你添加1900到$ code> $ year的同一时间

So to get a month number with 1 for January you need $mon+1, or you can just add one to $mday at the same time as you add 1900 to $year

像这样

use strict;
use warnings 'all';

use Time::Local;

my ($y, $m, $d) = (localtime)[5,4,3];

my $yesterday = timelocal(0, 0, 0, $d-1, $m, $y);
($y, $m, $d) = (localtime($yesterday))[5,4,3];
$y += 1900;
++$m;

print "Yesterday's Day: $d, Month: $m, Year: $y\n";



输出



output

Yesterday's Day: 11, Month: 11, Year: 2015

更好的方法是使用核心库 Time :: Piece 像这样

A better way is to use the core library Time::Piece like this

use strict;
use warnings 'all';

use Time::Piece;
use Time::Seconds 'ONE_DAY';

my $yesterday = localtime() - ONE_DAY;

printf "Yesterday's Day: %d, Month: %d, Year: %d\n",
    $yesterday->mday,
    $yesterday->mon,
    $yesterday->year;



输出



output

Yesterday's Day: 11, Month: 11, Year: 2015

这篇关于为什么perl的本地时间似乎输出错误的月份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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