Search code examples
perldate-formatdate-manipulation

Formatting a DateTime field in Perl


I am trying to use a string date, and format it to output correctly as "%Y%m%d_%H%M". Everything is outputting correct except for the day. It's actually returning the next day and I have no idea as to why it is. Below is the code and output.

my $currentTime = strftime("%Y%m%d_%H%M\n", gmtime(time));
my $hashTime    = strftime("%Y%m%d_%H%M\n", gmtime(UnixDate($user->{'add_date'}, "%s")));

$self->Print($user->{'add_date'} ."\n". $currentTime . "\n" . $hashTime);

Output:

2016-12-02 20:35:43 # Date from the Database 
20161202_2046  # Current GMTime
20161203_0235  # This should be 20161202_2035?

How come it's outputting as 03?


Solution

  • Ok, so I figured it out. For people that are curious, the new code is below.

    my $currentTime = strftime("%Y%m%d_%H%M\n", gmtime(time));
    my $hashTime    = UnixDate($user->{'add_date'}, "%Y%m%d_%H%M");
    
    $self->Print($user->{'add_date'} ."\n". $currentTime . "\n" . $hashTime);
    

    As you can tell, under $hashTime, when using UnixDate(), you don't need to use the strftime because it's already formatting it the way you need it.