1

I'm trying to insert some data to my database. The data contains also one date and time. So I need to insert that by converting into MySql DateTime format. I tried by using STR_TO_DATE, But it returns Date and Time Without AM OR PM.

Code Executed :

$sql = "INSERT into `projtemp` (`user_id`,`temp_name`,`processes`,`added`) VALUES('$uid','" . clean_data($tempName) . "','" . serialize($process) . "',STR_TO_DATE('$added', '%e/%c/%Y %r'))";
$result = $mysqli->query($sql) or die("Sql Error :" . $mysqli->error);

Query :

INSERT INTO `projtemp` (`user_id`,`temp_name`,`processes`,`added`) VALUES('0000000001','dsfwfwrfer','a:5:{i:0;s:11:"rgergergerg";i:1;s:29:"software requirement analysis";i:2;s:8:"regergre";i:3;s:16:"eqgerrrrrrrrrger";i:4;s:14:"ergergggggrreg";}',STR_TO_DATE('15/1/2014 11:34:21 AM', '%e/%c/%Y %r'))

Resultant Row :

enter image description here

I referred This Site, In that they says %r appends AM Or PM to Time But it didn't worked for me. Can anyone please help me to solve this issue.

1
  • @ peterm See the query given in the question. Commented Jan 15, 2014 at 6:57

2 Answers 2

2

For date without am/pm:

$datetime = date("Y-m-d H:i:s", strtotime($added));

With am/pm:

$datetime = date("Y-m-d H:i:s A", strtotime($added));

Finally your SQL stament will be:

$sql = "INSERT into `projtemp` (`user_id`,`temp_name`,`processes`,`added`) VALUES('$uid','" . clean_data($tempName) . "','" . serialize($process) . "','".$datetime."')";

For more details on date function refer: http://www.php.net/manual/en/function.date.php
*Note: If your column is of dataype datetime it won't insert am/pm with the date.

Sign up to request clarification or add additional context in comments.

6 Comments

Then what should I do if I want to insert AM Or PM
you have to change it to varchar then.
Your statement returns 0000-00-00 00:00:00 when I run.
When you are already having this string in date time format with am/pm then why you want it to convert again into datetime?
I wanted to convert because I used the datatype as datetime now I changed that to varchar but still I have problem with your code. If I pass 15/1/2014 12:49:53 it returns 1970-01-01 01:00:00 AM.
|
1

Try this code:

$timestamp = strtotime($added);

Then convert it to timestamp/datetime format using date(),

date("Y-m-d H:i:s A", $timestamp);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.