2014-04-15 14 views
6

Sto provando a fare un confronto di base di due date in Perl. Il DateTime corrente e il Tempo passato sono corretti ma la sottrazione fornisce risultati errati. La differenza dovrebbe essere ~ 24 ore, ma ritorna ~ 13 ore. Qualche idea sul perché e come risolverlo? Grazie.Perché il mio codice Time :: Piece dà strani risultati?

use Time::Piece; 

my $now = Time::Piece->new; 
my $then = Time::Piece->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S"); 
my $diff = $now - $then; 

print "Current time: $now\n"; 
print "Past time: $then\n"; 
print "Diff in Seconds:", $diff, "\n"; 
print "Pretty Diff:", $diff->pretty, "\n"; 

Results 
------ 
Current time: Tue Apr 15 16:13:39 2014 
Past time: Mon Apr 14 16:30:20 2014 
Diff in Seconds:49399 
Pretty Diff:13 hours, 43 minutes, 19 seconds 

risposta

9

I due punti temporali sono in fusi orari diversi. Quindi la differenza è in effetti corretta. Si può vedere che con

print $now->tzoffset, "\n"; # 7200 (I am in UTC +2 hence have 7200s offset) 
print $then->tzoffset, "\n"; # 0 

Quindi, fondamentalmente $then è un tempo UTC, mentre $now è in qualsiasi fuso orario vostro ambiente pensa che sia in. Per rimediare, è necessario decidere su quale fuso orario che si desidera.

+0

eccellente che è stato. grazie – user1768233

2

Come DeVadder ha già dichiarato, è il Time::Piece predefinito per UTC per i tempi analizzati.

Supponendo che si vuole tutto fatto utilizzando le localtime, si può effettivamente incoraggiare i tempi analizzati per ereditare il loro fuso orario, dal locale in questo modo:

use Time::Piece; 

use strict; 
use warnings; 

my $now = Time::Piece->new; 
my $then = localtime->strptime("2014-04-14 16:30:20", "%Y-%m-%d %H:%M:%S"); 
my $diff = $now - $then; 

print "Current time: $now\n"; 
print "Past time: $then\n"; 
print "Diff in Seconds:", $diff, "\n"; 
print "Pretty Diff:", $diff->pretty, "\n"; 

Uscite:

Current time: Tue Apr 15 17:12:08 2014 
Past time: Mon Apr 14 16:30:20 2014 
Diff in Seconds:88908 
Pretty Diff:1 days, 0 hours, 41 minutes, 48 seconds 
Problemi correlati