Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get yesterday's date using localtime?

Tags:

perl

localtime

How do I tweak this to get yesterday's date using localtime?

use strict;

sub spGetCurrentDateTime;
print spGetCurrentDateTime;

sub spGetCurrentDateTime {
my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $currentDateTime = sprintf "%s %02d %4d", $abbr[$mon], $mday, $year+1900; #Returns => 'Aug 17 2010' 
return $currentDateTime;
}

~

like image 260
jdamae Avatar asked Aug 17 '10 20:08

jdamae


People also ask

How to get yesterday's date in DateTime Python?

Use datetime. date. today() to get today's date in local time. Use today - datetime. timedelta(days=1) to subtract one day from the previous result today .

How do I get yesterday's date in Perl?

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');

What is Perl Localtime?

localtime EXPR localtime. Converts a time as returned by the time function to a 9-element list with the time analyzed for the local time zone. Typically used as follows: # 0 1 2 3 4 5 6 7 8 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);


2 Answers

use DateTime qw();
DateTime->now->subtract(days => 1); 

The expression on the second line returns a DateTime object.

like image 179
daxim Avatar answered Sep 27 '22 17:09

daxim


Solution suggested by most users is wrong!

localtime(time() - 24*60*60)

The worst thing you can do is to assume that 1 day = 86400 seconds.

Example: Timezone is America/New_York, date is Mon Apr 3 00:30:00 2006

timelocal gives us 1144038600

localtime(1144038600 - 86400) = Sat Apr 1 23:30:00 EST 2006

oops!

The right and the only solution is to let system function normalize values

$prev_day = timelocal(0, 0, 0, $mday-1, $mon, $year);

Or let datetime frameworks (DateTime, Class::Date, etc) do the same.

That's it.

like image 40
Pronin Oleg Avatar answered Sep 27 '22 17:09

Pronin Oleg