I want to know why the second line throws an error:
Yii::$app->formatter->dateFormat='yyyy-MM-dd';
echo Yii::$app->formatter->format('14/01/2017','date');
And why is there no error in this case?
Yii::$app->formatter->dateFormat='yyyy-MM-dd';
echo Yii::$app->formatter->format('10/07/2015', 'date');
Your date format is ambiguous . You're probably using DD/MM/YYYY format, but PHP interprets this as MM/DD/YYYY. There is no 14th month, so 14/01/2017 is incorrect date. 10/07/2015 does not throw any error, but it is probably incorrectly interpreted as 2015-10-07 instead of 2015-07-10.
You need to parse date before passing it to formatter:
Yii::$app->formatter->dateFormat = 'yyyy-MM-dd';
$date = DateTime::createFromFormat('d/m/Y', '14/01/2017');
echo Yii::$app->formatter->format($date, 'date');
Related
I have a MySQL date stored in DATETIME format. So I would like to know how to use date() in my Doctrine QueryBuilder's where clause. For example, 2013-02-01 12:51:17 is the date in MySQL. But I need to retrieve only the date. This is what I have tried:
$qb = $this->getEntityManager()->createQueryBuilder()
->select('t.balance','a.id','t.date')
->from('TestMainBundle:Transaction','t')
->groupBy('a.id')
->orderBy('a.id')
->where("t.date in date('t.date') ");
return $qb->getQuery()->getResult();
I received the following error:
QueryException: [Syntax Error]: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'date'
Hi You can use SUBSTRING to fix your probleme
->where('SUBSTRING(t.date, 1, 10) IN (:param)')
->setParameter('param', array('2017-04-06'))
As it is pointed out in the comments, you cannot use mysql-specific date() or date_format() functions in Doctrine.
But for the particular case of searching a certain date in the datetime field, you can treat a date like a string, and thus use LIKE operator
->Where('t.date LIKE :date')
->setParameter(':date', "$date%")
As of
But I need to retreive only the date
you just format the returned value using format("Y-m-d") method. i.e.
echo $row->getDate()->format("Y-m-d");
You don't need the "date" in your where clause.
Juste remove it like this :
->where('t.date in (:yourwanteddate)')
->setParameter('yourwanteddate', '2013-02-01 12:51:17');
I have Date and Time fields stored on mysql database, which have a very ugly unix format (applied by mysql).
In order to adapt this format to a more familiar one and echo it on the screen, I would fetch the date and bind it to a variable $mydate, so then I just format it this way.
$mydate= new DateTime($mydate);
$mydate=date_format($mydate,"d/m/Y");
This works perfect for me.
Now I have a new challenge: I want to build a table in which I have a Date and Time fields which I have to format somehow too. So hereĀ“s my code till now:
if ($arch = $pdo->prepare("SELECT date, time, info FROM tblinfo WHERE idinfo = ?")) {
$arch ->execute(array($idpac));
$data = $arch->fetchAll();
echo '<div class="cool_table" ><table><tr><td>TIME</td><td >DATE</td><td>INFO</td></tr>';
foreach ($data as $row){
echo '<tr>';
foreach ($row as $col){
echo '<td>'.$col.'</td>';
}
echo '</tr>';
}
echo '</table></div>';
}
So this generates a very cool table for me. But I cant seem to figure out how can I format the Date and Time using this code. Can someone help me with this one?
I recommend you format the date directly in the query, e.g.:
SELECT
DATE_FORMAT(date,'%m/%d/%Y') AS formateddate,
TIME_FORMAT(time,'%H:%i') AS formatedtime,
info
FROM tblinfo
WHERE idinfo = ?
EDIT
swapped arguments as from comment by #azirion
Have you tried googling LANGUAGE OBJECT OPERATION which yields PHP DateTime Format, and returns as one of the first results:
http://php.net/manual/en/datetime.format.php
Is that page any help? The technique generalizes. :)
I have the following line:
command.Parameters.Add("#date", SqlDbType.DateTime, 8).Value = date_of_trip;
where date_of_trip is a string containing 25-9-2013 (i.e. day-month-year)
This gives me an error message:
System.ArgumentException: Cannot convert 25-9-2013 to System.DateTime.
Parameter name: type ---> System.FormatException: String was not
recognized as a valid DateTime.
However, if date_of_trip is 1-1-2013, it seems to work perfectly!
You should parse the string to datetime before you send it to the db.
For example:
DateTime dt;
if(DateTime.TryParse(date_of_trip, out dt))
{
command.Parameters.Add("#date", SqlDbType.DateTime, 8).Value = dt;
// ...
}
else
{
// you should use a CompareValidator to check if it's a valid date
}
If you want to ensure that your given format will work even if the current-culture of the server will change you can use DateTime.TryParseExact with format "dd-MM-yyyy":
if (DateTime.TryParseExact(date_of_trip, "dd-MM-yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
{
// ...
}
I guess it's because the server expects the first parameter to be a month. Try to use a real DateTime or the format yyyy-mm-dd (i.e. 2013-09-25), which should always work.
I am using a DATE field in my MYSQL table, and pulling it through on a php page. The problem is it comes out as "2011-04-23"
Is there a way I can reformat this as 23/04/2011?
Thanks :)
date("d/m/Y", strtotime("2011-04-23"));
that should do it
date()
strtotime()
DATE_FORMAT(date,format)
Look here: http://dev.mysql.com/doc/refman/5.0/es/date-and-time-functions.html
Assuming variable $date contains your MySQL data:
$date = '2011-04-23';
$timezone = 'Europe/London'; // this is optional argument
$formatted = DateTime::createFromFormat('Y-m-d', $date, new DateTimeZone($timezone));
// or without the optional timezone - where php will assume the default timezone from your OS
$formatted = DateTime::createFromFormat('Y-m-d', $date);
echo $formatted->('d/m/Y');
I'm quite new to php and have been reading Larry Ullman book to develop a basic db site.
I have used the YUI Calendar pop up date picker to add a date to a text field called"date". The date format it enters is eg Thursday, 7 May 2009
I have tried many different ways to try and enter the date in to mysql db but it remains at 00 00 00 00 00 00
This is the code related to the date field I have,
// Check for a Date.
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo '<p><font color="red">Please enter a valid Date!</font></p>';
}
// Add the URL to the urls table.
$query = "INSERT INTO urls (url, title, description, date) VALUES ('$u', '$t', '$d', '$p')";
$result = #mysql_query ($query); // Run the query.
$uid = #mysql_insert_id(); // Get the url ID.
if ($uid > 0) { // New URL has been added.
I think I have provided all pertinent information but again apologies if this isn't helpful and I will do my best to provide yo with any other information you may require.
Thanks - Sean
If the format that your date picker is passing in is "Thursday, 7 May 2009", then the strtotime() and date() functions should work to give you a valid date to pass to MySQL:
$p = date("Y-m-d H:i:s",strtotime('Thursday, 7 May 2009'));
If your database field is a DATE, you probably only want the "Y-m-d" part. If it's a DATETIME, you'll want the "H:i:s" as well.
You probably need to format the date in the way that mysql expects it for that datatype, or else it cannot recognize it. You could use a regex or similar method to extract the component parts and format it according to the format of the MySQL DATETIME type.
EDIT: See http://dev.mysql.com/doc/refman/5.0/en/datetime.html for said format. Also, you might be better off storing the date/time as a unix timestamp, as that usually is easier to maintain.
the date format in mysql is YYYY-MM-DD, so change the way you accept data on php
if (eregi ("^([0-9]{2})/([0-9]{2})/([0-9]{4})$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';
Should be
if (eregi ("^([0-9]{4}/([0-9]{2})/([0-9]{2}))$", $_POST['date'],)) {
$p = escape_data($_POST['date'],);
} else {
$p = FALSE;
echo 'Please enter a valid Date!';