-1

Today I find following perl script running incorrect. Current actual datetime is 20140814 13:19 But it returns: 2014-7-14-13-19-15 (the month value 7 is 1 less than actual value 8)

MY OS: win7

sub GetFileNameDate {
    my ($sec,$min,$hour,$day,$month,$yr19,@rest) =   localtime;
    return sprintf "%s-%s-%s-%02d-%02d-%02d", ($yr19 + 1900), $month, $day, $hour, $min, $sec;
}
Amitabha
  • 1,693
  • 2
  • 25
  • 42
  • 2
    Where's the mistake? Is it the month? Because if it is, it's correct (month is 0..11, not 1..12, see http://perldoc.perl.org/functions/localtime.html). – AntonH Aug 14 '14 at 05:52
  • When a function returns a value that you suspect to be wrong, surely the most obvious next step to take is to read the documentation? – Dave Cross Aug 14 '14 at 09:25
  • 1
    Possible duplicate of [Why does perl's localtime seem to output the wrong month?](http://stackoverflow.com/questions/33676711/why-does-perls-localtime-seem-to-output-the-wrong-month) – ThisSuitIsBlackNot Nov 12 '15 at 17:01

3 Answers3

5

It is not incorrect it is like the month values starts from 0

sub GetFileNameDate {
    my ($sec,$min,$hour,$day,$month,$yr19,@rest) =   localtime;
    return sprintf "%s-%s-%s-%02d-%02d-%02d", ($yr19 + 1900), ($month +1), $day, $hour, $min, $sec;
}

$month is the month itself, in the range 0..11 with 0 indicating January and 11 indicating December.

You can check the manual

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
4

That is correct according to the docs for localtime:

$mday is the day of the month and $mon the month in the range 0..11, with 0 indicating January and 11 indicating December. This makes it easy to get a month name from a list.

However, to simplify your goal, I'd recommend using Time::Piece:

use strict;
use warnings;

use Time::Piece;

sub GetFileNameDate {
    return localtime->strftime("%Y-%m-%d-%H-%M-%S");
}

print GetFileNameDate(), "\n";

Outputs:

2014-08-13-23-42-56
Miller
  • 34,962
  • 4
  • 39
  • 60
0

Did you perhaps want POSIX::strftime?

use POSIX qw( strftime );

print strftime "%Y-%m-%d-%H-%M-%S", localtime;
LeoNerd
  • 8,344
  • 1
  • 29
  • 36