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;
}
~
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 .
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');
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);
use DateTime qw();
DateTime->now->subtract(days => 1);
The expression on the second line returns a DateTime
object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With