Formatting MySQL date - mysql

If I have a MySQL date as follows 2012-07-29 22:02:50, and I want this to be formatted to Jul 29 2012, is there an easy way to do this using a SELECT statement?
Currently my sql statement looks like this:
$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%Y-%m-%d\") AS Date FROM infoTable WHERE credential = '$credential'");
This outputs 2012-07-29

Try this:
$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%b %e %Y\") AS Date FROM infoTable WHERE credential = '$credential'");
Source

Change the DATE_FORMAT expression to:
DATE_FORMAT(Date,\"%b %e %Y\")
You can view all the possible formatting options at the DATE_FORMAT reference page.

$rs = mysql_query("SELECT Id, DATE_FORMAT(Date,\"%b %e %Y\") AS Date FROM infoTable WHERE credential = '$credential'");
http://www.w3schools.com/sql/func_date_format.asp

Related

MySQL does not order correctly using UNIX timestamp

I have this php code:
(from my database class)
$q = "SELECT * FROM" . CON_TBL. " WHERE a = $b ORDER BY thedate DESC";
$result = mysqli_query($this->connection, $q);
The dates (unix timestamp) on the DB are:
1138322340
1617584160
1617673680
759952800
I got this result:
30-Jan-1994 12:00
05-Apr-2021 20:48
04-Apr-2021 19:56
26-Jan-2006 18:39
The first date should be the last:
05-Apr-2021 20:48
04-Apr-2021 19:56
26-Jan-2006 18:39
30-Jan-1994 12:00
Any ideas what's going on?
The thedate column was a VARCHAR instead of an INT, once I changed the column to INT the ORDER was corrected.

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

Yii2 - Select where month and year using yii/db/Expression

In common query, we can use select a record or a lot of records using query like this
SELECT * FROM tagihan_cleaning
WHERE YEAR("ditagihkan_bulan") = 2017 AND
MONTH("ditagihkan_bulan") = 06
Now, In yii2, I have a dateInput , which is 06-2017.
Then, How to use Activerecord just query above.So far, I wonder like this:
TagihanCleaning::find()->where([
'ditagihkan_bulan' => MONTH('ditagihkan_bulan')
])->all();
Please advise
Assuming you dateinput is string name $your_date_input, for an activeRecord, you could use
a liter where and binding
TagihanCleaning::find()->where(' YEAR("ditagihkan_bulan") = YEAR(str_to_date(:your_date_input1, "%m-%Y")
AND MONTH("ditagihkan_bulan") = MONTH(str_to_date(:your_date_input2, "%m-%Y") )
->bindValue(':your_date_input1', $your_date_input)
->bindValue(':your_date_input2', $your_date_input)
->all();
you can use directQuery:
Yii::$app->db->createCommand('SELECT * FROM tagihan_cleaning
WHERE YEAR("ditagihkan_bulan") = 2017 AND
MONTH("ditagihkan_bulan") = 06')
->queryAll();
With Prepared statement:
$post = Yii::$app->db->createCommand('SELECT * FROM tagihan_cleaning WHERE YEAR("ditagihkan_bulan")=:year AND MONTH("ditagihkan_bulan")=:month')
->bindValue(':year', '2017')
->bindValue(':month', '06')
->queryOne();

SQL and perl time formatting

I cant seem to figure out a way to format a string in perl to use in a MySQL DateTime() field.
my $time = "Sat Jun 29 11:20:28 2013 -0400"
and i need to format time so it can be entered into a MySQL DateTime() field
Format: YYYY-MM-DD HH:MM:SS
i plan to enter this using perl mysql module
$createQuery = "INSERT INTO something (dated) Values(?) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You don't have to do any formatting yourself.
$time = time;
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
If you do really need a string and your data source is not a unix timestamp, just use any of the formats that MySQL understands.
$time = '2013-06-29 18:50:00';
$createQuery = "INSERT INTO something (dated) Values( FROM_UNIXTIME( ? )) ";
$sqlQuery = $dbh->prepare($createQuery);
$sqlQuery->execute($time);
You can use the core module Time::Piece which has been part of the Perl core since 5.9 : corelist .
use Time::Piece;
my $time = q(Sat Jun 29 11:20:39 2013 -0400);
my $t = Time::Piece->strptime($time, '%a %b %d %H:%M:%S %Y %z');
print $t->strftime("%Y-%m-%d %H:%M:%S\n");
If you don't have perl 5.9, Date::Manip will sort you:
$date_as_mysql_likes = UnixDate(ParseDate($your_date_here), '%Y-%m-%d %H:%M:%S');

php mysql group by date with yyyy-mm-dd format

I had a mysql table called events with the fields: id, date, and name.
The date field has the format yyyy-mm-dd hh::mm:ss edit: meaning it is in datetime format
I want to group the events by day, and I wasn't sure how to approach this- is there a way to select only the month and day from the field? or should i use PHP after I select all the "events"
my end goal is to have something like this:
March 10th:
event1,
event2
March 11th:
event4,
event5
I found MySQL select using datetime, group by date only but I'm not sure how to implement it:
SELECT DATE_FORMAT(date, '%H%i'), DATE_FORMAT(date, '%M %D'), name FROM events ORDER BY date
Thanks!
EDIT:
ended up using this:
$sql = "select team1, team2, DATE_FORMAT(date,'%Y-%m-%d') as created_day FROM games WHERE attack = '1' GROUP BY created_day";
$result = mysql_query($sql);
$curDate = "";
while (list($team1, $team2, $date) = mysql_fetch_row($result))
{
if ($date != $curDate)
{
echo "$date --------\n";
$curDate = $date;
}
echo "game data: $team1 $team2";
}
If you use group by you will not get one row out of it. So the way you want is not possible through Group By AFAIK.
$query = "SELECT distinct(DATE_FORMAT(date, '%M %D')) as d FROM yourtable";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo $row['d']
$sql = "SELECT * FROM yourtable WHERE DATE_FORMAT(date, '%M %D')='$row[d]'";
$rs = mysql_query($query);
while($r = mysql_fetch_assoc($rs)) {
echo "event";
}
}
You should indeed use php to get this done. But since most of current system sepate logic from display, I'd use only one pass and not (NUMBER OF DAYS + 1) SELECTs, and prepare an array that I can reuse later for my display.
$query = "SELECT DATE_FORMAT(date, '%M %D') as d, name FROM yourtable ORDER BY date";
$foo=array();
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
//some logic to test if it's safe to add the name
$foo[$row['d']][]=$row['name'];
}
And then when i'd need it (through a template or your "view")
foreach($foo as $date => $events) {
echo $date . ":\n\t";
echo implode(",\n\t", $events);
echo "\n";
}
so it fits the format you set to yourself.
Hope that helped
I think from that question/answer, you can get something like this instead
March 10th, event1
March 10th, event2
March 11th, event4
March 11th, event5
It does not really 'group' dates as your wish but I think you can use php to continue from this result.
I agree with Kharaone, separate logic from display. That being said, I think that something similar to this query might be what you are looking for:
SELECT A FROM
(
SELECT DATE_FORMAT(date,'%M %D:') AS A, DATE(date) AS B, 1 AS C FROM games GROUP BY DATE(date)
UNION ALL
SELECT name AS A, DATE(date) AS B, 2 AS C FROM games
) X
ORDER BY B, C ASC;