Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Answer: How can I format the output of localtime?

by Mago (Parson)
on Jul 08, 2003 at 20:35 UTC ( #272453=categorized answer: print w/replies, xml ) Need Help??

Q&A > dates and times > How can I format the output of localtime? - Answer contributed by Mago

sub TimeStamp { my($format) = $_[0]; my($return); (my $sec,my $min,my $hour,my $mday,my $mon,my $year,my $wday +, my $yday, my $isdst) = localtime(); $year = $year + 1900; $mon = $mon + 1; if (length($mon) == 1) {$mon = "0$mon";} if (length($mday) == 1) {$mday = "0$mday";} if (length($hour) == 1) {$hour = "0$hour";} if (length($min) == 1) {$min = "0$min";} if (length($sec) == 1) {$sec = "0$sec";} if ($format == 1) {$return = "$year\-$mon\-$mday $hour\:$min +\:$sec";} if ($format == 2) {$return = $mon . $mday . $year;} if ($format == 3) {$return = substr($year,2,2) . $mon . $mda +y;} if ($format == 4) {$return = $mon . $mday . substr($year,2,2 +);} if ($format == 5) {$return = $year . $mon . $mday . $hour . +$min . $sec;} if ($format == 6) {$return = $year . $mon . $mday;} if ($format == 7) {$return = $mday .'/'. $mon .'/'. $year .' + '. $hour .':'. $min .':'. $sec;} if ($format == 8) {$return = $year . $mon . $mday . $hour . +$min;} if ($format == 9) {$return = $mday . '/' . $mon . '/' . $yea +r;} return $return; }

Replies are listed 'Best First'.
Re: Answer: How can I format the output of localtime?
by cLive ;-) (Prior) on Feb 09, 2004 at 16:58 UTC
    Dude, I really think you need to read up on sprintf!
    sub TimeStamp { my($format) = $_[0]; my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); $year+=1900; $mon++; if ($format == 1) { return sprintf("%4d-%02d-%02d %02d:%02d:%02d",$year,$mon,$mday +,$hour,$min,$sec); } elsif ($format == 2) { return sprintf("%02d%02d%4d",$mon,$mday,$year); } elsif ($format == 3) { return sprintf("%02d%02d%02d",$year%100,$mon,$mday); } elsif ($format == 4) { return sprintf("%02d%02d%02d",$mon,$mday,$year%100); } elsif ($format == 5) { return sprintf("%4d%02d%02d%02d%02d%02d",$year,$mon,$mday,$hou +r,$min,$sec); } elsif ($format == 6) { return sprintf("%4d%02d%02d",$year,$mon,$mday); } elsif ($format == 7) { return sprintf("%02d/%02d/%4d %02d:%02d:%02d",$mday,$mon,$year +,$hour,$min,$sec); } elsif ($format == 8) { return sprintf("%4d%02d%02d%02d%02d",$year,$mon,$mday,$hour,$m +in); } else { return sprintf("%02d/%02d/%4d",$mday,$mon,$year); } }
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (1)
As of 2020-10-25 20:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (249 votes). Check out past polls.

    Notices?