Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Transforming date

Status
Not open for further replies.
Joined
Aug 22, 2002
Messages
113
Location
FR
Hello,

I have a variable with this data: “Sun Feb 29 15:51:32 2004”. I would like to transform it into two variables with the following formats:

Var1: 29/02/2004
Var2: 15:51:32


Could you guys help me doing this?

Thanks for your help.
 
This should do it:
Code:
$string = "Sun Feb 29 15:51:32 2004";
if ($string =~ /^([\w]{3})(\s)([\w]{3})(\s)([\d]{1,2})(\s)([\d]{2}\:[\d]{2}\:[\d]{2})(\s)([\d]{4})$/){
        %month_a = ('Jan', '01', 'Feb', '02', 'Mar', '03', 'Apr', '04', 'May', '05', 'Jun', '06', 'Jul', '07');
                                                                                                                                                             
        $dow = $1;
        $month = $3;
        $day = $5;
        $time = $7;
        $year = $9;
                                                                                                                                                             
        $month = $month_a{'Feb'};
        $var1 = "$5/" . "$month/" . "$year";
        $var2 = $time;
                                                                                                                                                             
        print "var1 = $var1\nvar2 = $var2\n";
}
else{
        print "Incorrect format string.";
}
Hope it helps.

Sean.
 
Thank you very much Sean.

The date string is never the same so I modified your code a bit to have the month part transformed dynamically.

Here's the resulting code:

Code:
$string = "Mon Mar 03 15:51:32 2004";
if ($string =~ /^([\w]{3})(\s)([\w]{3})(\s)([\d]{1,2})(\s)([\d]{2}\:[\d]{2}\:[\d]{2})(\s)([\d]{4})$/){
        %month_a = ('Jan', '01', 'Feb', '02', 'Mar', '03', 'Apr', '04', 'May', '05', 'Jun', '06', 'Jul', '07');
                       
        $dow = $1;
        $month = $3;
        $day = $5;
        $time = $7;
        $year = $9;
        $month = $month_a{$month};
        $var1 = "$5/" . "$month/" . "$year";
        $var2 = $time;
                         
        print "var1 = $var1\nvar2 = $var2\n";
}
else{
        print "Incorrect format string.";
}

Thanks again.
 
How about something simpler using the Date::Manip module?

Code:
use Date::Manip;

$date = ParseDate("Sun Feb 29 15:51:32 2004");
$date =~ /(.{4})(.{2})(.{2})(.*$)/;
$var1 = "$3/$2/$1";
$var2 = "$4";

print "$var1\n$var2\n";
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top