Jump to content

Formatting date


johnrb87

Recommended Posts

Hi there

 

I wonder if anyone can help.

 

I have a HTML form which i'm posting the contents of to a PHP file

 

At the moment, one of the fields i'm posting is called `date` and the value looks like

 

Jul 14, 2010

 

At in my PHP code I have

 

<?php
$date = $_POST['date'];
?>

 

is it possible to get PHP to convert the date format

 

Jul 14, 2010

 

to

 

2010-07-14

 

Any help would be great as im really struggling to do this basic task

 

Thanks

 

John

Link to comment
Share on other sites

After some testing I have come up with a pretty basic way of doing it. The only reason i didn't do it completely with substr is: the day could be entered without the starting zero.

It does a check for that with strlen and fixes that problem.

<?php
$months = array("Jan" => '01', "Feb" => '02', "Mar" => '03', "Apr" => '04', "May" => '05', "Jun" => '06', "Jul" => '07', "Aug" => '08', "Sep" => '09', "Oct" => '10', "Nov" => '11', "Dec" => '12');
$date = "Jul 4, 2010";
$year = substr($date, -4);
$month = substr($date, 0, 3);
preg_match("/ (\d{1,2}),/", $date, $matches);
$day = $matches[1];
if(strlen($day)==1) $day = "0".$day;
$date = $year.'-'.$months[$month].'-'.$day;
echo $date;
?>

 

Good luck with the rest of your code.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.