You are here iC Home > Perl > Date & Time in Perl > Format Time

Perl

4.2 Format Time

09.05.2008
4.1 Date & Time Calculations (Date::Manip) [  up  ] - [ a - z ] - [ search PC ] - [ top ] 4.3 Calculate Easter Day

Problem

You want to generate a MySQL 4.x compatible time string. You also may move back and forward in time by adding specfic amount of seconds where installing fat Date modules would be an overkill.

Output

Now:            20060703103634
Before 1 hour:  20060703093634
Before 6 hours: 20060703043634

The Code

#!/usr/bin/perl -w
use strict;

print 'Now:            ', &formatTime(str => scalar localtime(time() -     0)), "\n";
print 'Before 1 hour:  ', &formatTime(str => scalar localtime(time() -  3600)), "\n";
print 'Before 6 hours: ', &formatTime(str => scalar localtime(time() - 21600)), "\n";

sub formatTime(%) {
	my %args = @_;
	$args{'str'} ||= ''; # e.g. Mon Jul 3 12:59:28 2006

	my @elems = ();
	foreach (split / /, $args{'str'}) {
		next unless $_;
		push(@elems, $_);
	}

	my ($weekday, $month, $mday, $time, $yyyy) = split / /, join(' ', @elems);

	my %months = (  Jan => 1, Feb => 2, Mar => 3, Apr =>  4, May =>  5, Jun =>  6,
			Jul => 7, Aug => 8, Sep => 9, Oct => 10, Nov => 11, Dec => 12 );

	my $s  = substr($time, 6,2);
	my $m  = substr($time, 3,2);
	my $h  = substr($time, 0, 2);
	my $dd = sprintf('%02d', $mday);

	my $mm_num = sprintf('%02d', $months{$month});

	#my $formatted = "$yyyy\-$mm_num\-$dd $h:$m:$s";
	my $formatted = "$yyyy$mm_num$dd$h$m$s";

	$formatted;
}

Download → files/format time pl.txt

4.1   Date & Time Calculations (Date::Manip)
4.2   Format Time
4.3   Calculate Easter Day
4.4   Calculate Weekday
4.5   Related Date & Time Links



See also:



Advanced search tips
4.1 Date & Time Calculations (Date::Manip) [  up  ] - [ top ] 4.3 Calculate Easter Day



[ home ] - [ search ] - [ feedback ]

copyright by reto - created with mytexi