Dieser Post wurde aus meiner alten WordPress-Installation importiert. Sollte es Darstellungsprobleme, falsche Links oder fehlende Bilder geben, bitte einfach hier einen Kommentar hinterlassen. Danke.
Kids are discriminated for being kids. They're not allowed to smoke, drink alcohol and use various internet offers. but writing "not for kids" on a homepage barely fulfills legal and real life requirements, software has to calculate the age based on a known date of birth.
mySQL has a DATE_INTERVAL command but should be considered very bad style to submit simple math issues to the database unless you need to fetch some stored data. Better use Date::Calc and pure Perl:
use Date::Calc qw(Today date_check N_Delta_YMD);=pod
=head2 calculate_age
$age = calculate_age($date_of_birth);
Return the current age based on the given date of birth (YYYY-MM-DD).
Sample:
calculate_age('1979-08-20');
Returns 33 (at least today).
=cut
sub calculate_age my @dob = split(/\-/, shift);
# Check if given date of birth is valid. return unless check_date(@dob);
# Calculate the years, months and days since the given date of birth my @age = N_Delta_YMD(@dob, Today());
return $age[0];}
check_date is strongly suggested because all (other) Date::Calc functions will die in case of any invalid date passed.
6 Kommentare. Schreib was dazu-
Jay
6.03.2013 21:36
Antworten
-
Sebastian Willing
7.03.2013 6:46
Antworten
-
Sebastian Willing
7.03.2013 6:46
Antworten
-
Dave Cross
7.03.2013 8:38
Antworten
-
Sebastian Willing
7.03.2013 8:46
Antworten
-
Sebastian Willing
7.03.2013 8:46
Antworten
Or use Time::Piece + Time::Seconds (part of core since 5.10)
[Imported from blog]
[Imported from blog]
I only ever use Time::Piece or DateTime for time and date calculations these days.
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Time::Piece;
say calculate_age('1979-08-20');
sub calculate_age {
my $dob = Time::Piece->strptime(shift, '%Y-%m-%d');
my $age = Time::Piece->localtime - $dob;
return int $age->years;
}
[Imported from blog]
[Imported from blog]