Symfony2 Date transforming (dd.mm.yyyy) to (yyyy-mm-dd) - php

I'm new with Symfony2 and PHP and I've a question pertaining to formatting dates.
I have a form where the user can enter a date in this format: dd.mm.yyyy. The SQL Database uses this format: yyyy-mm-dd. Now when make an sql query i get a mismatch of course.
public function getFindingPatientQuery($birthdate){
$em = $this->getEntityManager();
$query = $em->createQuery(
'SELECT p
FROM Data\LiveBundle\Entity\DataAPatient p
WHERE p.pDateOfBirth = :birthdate'
)->setParameter('birthdate', $birthdate| ('Y-m-d'));
return $query;
}
What's the easiest way to transform the input dd.mm.yyyy date to the demanded format yyyy-mm-dd? Does there exist some global solution if I'd need this transformation more than 1 time? I prefer a non-JavaScript solution.
I found some answer here in the forum but nothing worked.
Thanks

Try to indicate parameter type and make sure the $birthdate variable is a \DateTime object:
use Doctrine\DBAL\Types\Type;
...
->setParameter('birthdate', $birthdate, Type::DATE);

May be your birthdate isn't the type date ?
$date = DateTime::createFromFormat('j-M-Y', $birthdate);
echo $date->format('Y-m-d');

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

Trying to make a stored Datetime value shorter with SQL Convert function

I'm new to using the convert function. I'm trying to make a datetime value from my table shorter. Currently my datetime values look something like this, 2016-10-14 16:51:41, but I'd like to make it look something like mm/dd/yy.
I don't know if this is the right approach (must not be since it doesn't work), but I've generated a query using the convert function and then fetching the data with a mysqli_fetch_array.
Here's the code I'm using:
$sql = "SELECT id, time, CONVERT(VARCHAR(11), time) as something FROM tableName";
$query = mysqli_query($db, $sql);
$statusnumrows = mysqli_num_rows($query);
// Gather data about parent pm's
if($statusnumrows > 0){
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$time= $row["time"];
}
}
Time is the name of the column which has the datetime type.
Thanks in advance, for suggestions/advice.
You should store datetime in your DB in proper data types like datetime etc.
As I can see you are using PHP, if you need to OUTPUT this datetime in some interface (f.e. HTML page), you should use PHP functions to convert date in format you need. That is the good practice
DB should STORE the data but formatting is front-end problem.
Simple example of strtotime() and date():
$Date = "2016-10-15";
$newDate = date("m/d/Y", strtotime($Date));
You can read docs on the PHP site: strtotime and date
If 2012+ you could use format (not very efficient but does offer some other possibilities)
Declare #Date DateTime = GetDate()
Select UsingFormat = Format(#Date,'MM/dd/yy')
,UsingConvert1 = convert(varchar(10),#Date,1)
,UsingConvert101 = convert(varchar(10),#Date,101)
Returns
UsingFormat UsingConvert1 UsingConvert101
10/15/16 10/15/16 10/15/2016
Use style 1 in Convert function for mm/dd/yy format
select CONVERT(VARCHAR(20), [time],1)
From yourtable
If you want mm/dd/yyyy format then use 101 style
select CONVERT(VARCHAR(20), [time],101)
From yourtable
MSDN link for Convert function with various style : CONVERT

Get date and time retrieved from database into a datetime input

I'm trying to retrieve a Datetime value from my database and place it in an html input with a date type but it doesn't show anything.
$resQuery = mysql_query("SELECT * FROM reserveringen WHERE id = $ID");
while ($resInfo = mysql_fetch_array($resQuery))
{
$dateTime = $resInfo[3];
}
<?php echo "<input name='dateTime' type='datetime-local' value='$dateTime'"?>
Also when I F12 I get this error: The specified value "2525-0505-16161616 0606:0505" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".
This fixed it for me guys!
I changed my query to:
SELECT *, DATE_FORMAT(Datum, '%Y-%m-%dT%H:%i') AS Datum_conv FROM reserveringen WHERE id = $ID
The problem is that when you was writing data into database you used wrong date format. Look carefully at datetime value:
2525-0505-16161616 0606:0505
It must be
25-05-16 06:05
What you did when saving data is using these date format:
date('dd-mm-yyyy HH:ii')
instead of this
date('d-m-Y H:i');

php insert prepared stmt

My code looks like:
$sql_ = $this->db->prepare("SELECT * FROM user");
$sql_->execute();
$user = $sql_->fetchAll();
$sql_insert_blog = $this->db->prepare("INSERT INTO
blog
(blog_title,blog_author,blog_content,blog_tags,blog_create,blog_update)
VALUES
(:1,:2,:3,:4,:5,:6)");
$sql_insert_blog->execute(array(
":1"=>$title,
":2"=>$author,
":3"=>$content,
":4"=>$tags,
":5"=>$date_create,
":6"=>$date_update
));
So the first sql statement is to proof if the database coneccion is active. It works when i use
print_r($user)
Th second one is the statement thats not been executed.
I have a controller that calls this function on a model, and gives all the info from the form to this function like
function newBlogEntry()
{
$title = $_POST["input_blog_title"];
$author = $_POST["input_blog_author"];
$content = $_POST["input_blog_content"];
$tags = $_POST["input_blog_tags"];
$date_create = date('m/d/Y h:i:s a', time());
$date_update = $date_create;
$this->model->newBlogEntry($title,$author,$content,$tags,$date_create,$date_update);
}
and the function on this model is actually called. i can select all users from db.
i allready checked all the parameters, and also every parameter can be null so, even if the form is emtpy it should be a insert in the database(This is just for testing).
But there is no entry in the database...
So my question is: what am i doing wrong here?
It would appear that MySQL doesn't like your date values. The default format for dates-as-strings in MySQL is YYYY-MM-DD HH:MM:SS, according to the docs; a string that looks like this will automatically be parsed as a date.
use (?,?,?,?,?,?) instead of (:1,:2,:3,:4,:5,:6)
and
$sql_insert_blog->execute(array($title, $author, $content, $tags, $date_create, $date_update));
and
dates should be strings with Y-m-d H:i:s php date() format

Mysql query on date function

I have table "movie" which consists of a field "date of release"
how do I query that, which movie hit's the theatre every friday?
$r = false;
$movie = false;
$r = query("SELECT id FROM movie WHERE dateOfRelease='friday'");
$movieInfo = query("SELECT * FROM movie WHERE id='{$r[\'id\']}'");
Made some assumptions because your question has very little information, hopefully this will help
You can find out this week's friday like this:
$datefriday=date('Y-m-d', strtotime('next friday'));
Assuming you have a date() type field in your database, you can use a query like:
SELECT column1,column2,column3,column4 from movie where date_of_release = $datefriday
I have no idea if you use mysqli, pdo or even mysql. So I cant let the query run in php for you. The query has to look like this though. If you want the friday of the week after that, you can use:
$date_next_friday=date('Y-m-d', strtotime($datefriday.'+ 7 days'));
This should help you.

Categories