0

I have a strange problem . I am trying to insert some values to database with respective date . In HTML form, the date format is mm/dd/yyyy format. I converted this format to mysql yyyy-mm-dd format using the following PHP (from stackoverflow answer):

echo $date1 = str_replace("/","-",$_POST['date']); echo $date = date('Y-m-d', strtotime($date1)); 

But the above echo , when I run the code it shows like this: 07-30-2012 1970-01-01

1
  • The answer you link to converts dd/mm/yyyy to yyyy-mm-dd, and that is different from mm/dd/yyyy input. Commented Jul 30, 2012 at 5:44

6 Answers 6

3

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. See http://php.net/manual/en/function.strtotime.php for details.

So even you are passing '07-30-2012' as an input, it is considering 07 as date, 30 as month hence you are getting incorrect results.

Following should work

echo $date = date('Y-m-d', strtotime($_POST['date'])); 
Sign up to request clarification or add additional context in comments.

Comments

1
echo $date = preg_replace('/^(\d\d)\/(\d\d)\/(\d{4})$/', '$3-$1-$2', $_POST['date']); 

I think this code should work fine, but of course you must do all necessary checks before insert it into database.

2 Comments

Thanks CyberDemon...its working. Can you explain or just give a help link,I will b grtful to u
I had used regular expression to modify string (reorder numbers and replace slash to dash).
1
echo $date1 = str_replace("/","-","$_POST['date']"); echo $date = date('Y-m-d', strtotime($date1)); 

put double quotes in date then you get perfect result

Comments

0

I've just tried :

$date = "30/07/2012"; echo $date1 = str_replace("/","-",$date); echo '<br />'; echo $date = date('Y-m-d', strtotime($date1)); 

And it's actually returning :

30-07-2012 2012-07-30 

You should check your $_POST['date'] format.

Comments

0

echo $date = date('Y-m-d', strtotime($_POST['date']));

Your first line is incorrect, which returns false, which (converted to an integer) is 0, 0 is the beginning of time on a linux machine! (hence 1970-01-01)

Comments

0

Your input is in mm/dd/yyyy format, that means you should use slashes / You would need to change to dashes if you were using dd-mm-yyyy format, as is shown in the answer you link to. So in your case you should not replace the /.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.