I have stored three essential timestamps and times into my database table, format as follows:
mysql> select receivedtime, requesttime, sla from table;
+---------------------+---------------------+----------+
| receivedtime | requesttime | sla |
+---------------------+---------------------+----------+
| 2013-05-26 22:37:04 | 2013-05-26 12:37:04 | 02:59:59 |
| 2013-05-26 14:36:44 | 2013-05-21 12:39:09 | 72:00:00 |
+---------------------+---------------------+----------+
2 rows in set (0.00 sec)
I need to put a few conditions like below:
difference = (receivedtime - requesttime);
if [difference <= sla]
{
show meet
} else {
show don't meet
}
legend:
receivedtime [timestamp] as because days
requesttime [timestamp] as because days
sla [time] as because hour
I have checked UNIX_TIMESTAMP() of mysql, strtotime() of php and few other tries.
I also have checked several threads # stackoverflow.com, but I can't find proper solution.
Any ideas...!
Check TIMESTAMPDIFF() and SEC_TO_TIME() functions:
SELECT
`receivedtime`,
`requesttime`,
`sla`,
(SEC_TO_TIME(TIMESTAMPDIFF(SECOND, `requesttime`, `receivedtime`)) < `sla`) as `meet`
FROM
`table`;
Try
SELECT receivedtime,
requesttime,
CASE WHEN TIMESTAMPDIFF(SECOND, requesttime, receivedtime) < TIME_TO_SEC(sla)
THEN 'meet' ELSE 'don\'t meet' END sla
FROM table1
Here is SQLFiddle demo
Try selecting from your database like this ...
select TIMESTAMPDIFF(SECOND, receivedtime, requesttime) as difference, TIME_TO_SEC(sla) as slasecs from table
and then you can do your.
if [difference <= sla]
{
show meet
}
else
{
show don't meet
}
That is a datetime field, not a timestamp field. You should start with reading up on what a timestamp is.
you can figure out the difference by converting to timestamp then subtracting.
$recieved = strtotime($res['receivedtime']);
$requested = strtotime($res['requesttime']);
$difference = $recieved - $requested;
if($difference <= $sla){
//do stuff
}
You can do that in SQL
SELECT (UNIX_TIMESTAMP(receivedtime) - UNIX_TIMESTAMP(requesttime)) AS difference FROM table
it gives you the difference in seconds.
Try this
select TIMESTAMPDIFF(SECOND,`requesttime`,`receivedtime`) as timeDiff FROM `table`
WHERE TIMESTAMPDIFF(SECOND,`requesttime`,`receivedtime`) > TIME_TO_SEC(`sla`)
SEE SQL FIDDLE
You can find relevant in mysql documentation
Related
I have the following structure as a table, I want to select the record from one day before, I have tried the following query for selecting the record.
SELECT slot_date, slot_time FROM slot_booking WHERE slot_date =
DATE_SUB(CURDATE(), INTERVAL 24 HOUR)
assume if today is (2018-04-03) time is 09 (24hr Format) I want to select a record from DB 2018-04-04 TIME between 09:00:00 to 9.30:00
i am struggling with compare time field, if you have any suggestion or solution post you answer
Concat date and time fields, use str_to_date to convert to datetime then use date_add or date_sub as required
SET #DT = '2018-04-14';
SET #T = '09:00:00';
set #now = '2018-04-13 09:00:00';
SELECT STR_TO_DATE(CONCAT(#DT,#T),'%Y-%m-%d%H:%i:%s') dt,
case when STR_TO_DATE(CONCAT(#DT,#T),'%Y-%m-%d%H:%i:%s')
between date_add(#now, interval 24 hour) and date_add(date_add(#now, interval 24 hour),interval 30 minute) then 'true'
else 'false'
end as inrange;
+---------------------+---------+
| dt | inrange |
+---------------------+---------+
| 2018-04-14 09:00:00 | true |
+---------------------+---------+
1 row in set (0.00 sec)
Please i want to create a php code to check if time has expired or still active based on the start date and end time that users specified.
Below is the database structure and sample php code which i tried.
game_config
game_id | start_date | start_t | start_h | end_time | end_h | status
--------|------------|---------|---------|----------|-------|---------
100 | 03/26/2018 | 10:45 | PM | 12:30 | AM | 0
101 | 03/27/2018 | 09:23 | AM | 11:10 | AM | 0
Php code sample
<?php
$conf_execution_date = date('m/d/Y'); /*Current date*/
$conf_execution_meridiem = date('A'); /*Current meridiem*/
$conf_execution_timer = date('h:m'); /*Current time*/
$conf_execution_proccess = false; /*Proceed or not*/
$conf_handler = $appconn->prepare("
SELECT * FROM game_config WHERE game_id = :game_id AND start_date = :start_dateAND start_t = :start_t AND status = 0 LIMIT 1
");
$conf_handler->bindParam(":game_id", 100);
$conf_handler->bindParam(":start_date", $conf_execution_date);
$conf_handler->bindParam(":start_t", $conf_execution_meridiem);
$conf_handler->execute();
$appconf = $conf_handler->fetch(PDO::FETCH_OBJ);
if($appconf){
$config_start_time = strtotime($appconf->start_t);
$config_end_time = strtotime($appconf->end_time);
$current_time = strtotime($conf_execution_timer);
if($appconf->start_h == $conf_execution_meridiem){ /*AM-PM*/
if($config_start_time >= $current_time){ /*Check if the start time is now o still active*/
$conf_execution_proccess = true;
}
}
if($appconf->end_h == $conf_execution_meridiem){ /*AM-PM*/
if($config_end_time >= $current_time){ /*Check if the time has ended*/
$conf_execution_proccess = false;
}
}
if($conf_execution_proccess == true){
echo 'YES THE GAME IS STILL ACTIVE';
}else{
echo "NO GAME HAS ENDED";
}
}
?>
Assuming your start_date column is type VARCHAR():
Assuming your end_time is always later in the day than your start_time:
You can use this sort of query to get a starting and ending DATETIME value for each row of your table. It glues together the date, the time, and the AM/PM fields and converts them to DATETIME. (http://sqlfiddle.com/#!9/2d84ea/1/0)
SELECT game_id,
STR_TO_DATE(CONCAT(start_date,'-',start_t,start_h), '%m/%d/%Y-%h:%i%p') start_ts,
STR_TO_DATE(CONCAT(start_date,'-',end_time,end_h), '%m/%d/%Y-%h:%i%p') end_ts,
status
FROM game_config
Then you can compare those start_ts and end_ts values to NOW() by appending this line to your query
Then you can fill out your query with the criteria you need, giving this query.
SELECT game_id,
STR_TO_DATE(CONCAT(start_date,'-',start_t,start_h), '%m/%d/%Y-%h:%i%p') start_ts,
STR_TO_DATE(CONCAT(start_date,'-',end_time,end_h), '%m/%d/%Y-%h:%i%p') end_ts,
status
FROM game_config
WHERE game_id = : gameid AND status = 0
HAVING start_ts <= NOW() and NOW() < end_ts
LIMIT 1
But, your start and end times sometimes span midnight, which means your end_ts needs to be on the next day. That makes your date-checking logic quite a bit trickier. You'll have to do some sort of conditional expression in which you do + INTERVAL 1 DAY to your end_ts if it is before your start_ts.
You will be much better off (#eggyal pointed this out in his comment) if you put the following columns in your table.
game_id int
start_ts timestamp of start
end_ts timestamp of end
status int
Then you don't have to worry about all the stuff about making a proper timestamp from three different columns, and you don't have to do anything special when the start and end times span midnight.
And, this will work intuitively no matter what timezone your users are in.
i create a event for calculate a birthday , for example:
birthday date = 1990-09-07
now date = 2013-09-05
my query :
SELECT id FROM user WHERE ( birthday - NOW() ) <= 7
this query is mistake
I think DAYOFYEAR function is more suitable for you:
mysql> SELECT DAYOFYEAR('2000-09-07') - DAYOFYEAR(now()) AS diff;
+------+
| diff |
+------+
| 3 |
+------+
Today is 2013-09-05, it gave 3 days. Now you can compose the condition. Please, mind 1 day in the leap year.
You said its for birthday so you must consider month and date as date can be repeat for every month..
So try something like below, for year difference.
SELECT
(YEAR(birthdate) - YEAR(NOW())) AS yeardifference
FROM
table
WHERE
MONTH(birthdate) = MONTH(NOW())
AND
DATEDIFF(birthdate, NOW()) <= 7
For day difference
SELECT
DATEDIFF(birthdate, NOW())
FROM
table
WHERE
MONTH(birthdate) = MONTH(NOW())
AND
DATEDIFF(birthdate, NOW()) <= 7
The Dayofyear function would be useful, just to put it in context with your requirement
SELECT id FROM user WHERE (DAYOFYEAR(birthday) - DAYOFYEAR(NOW())) <= 7
I think your query should be something like
SELECT id
FROM user
WHERE ( DAYOFYEAR(birthday) - DAYOFYEAR(NOW()) <= 7)
I have a database holding two bits of information. from date to date. I need this entry to appear in my calender on every day, but I can only manage to get to appear on the first and last date.
example of DB:
job_no | date1(from)| date2(to)
________________________________
1 |2013-01-28 | 2013-02-03
2 |2013-01-14 | 2013-01-18
Edit for question. the search bar I have allows for ONE date input and the the calender finds entries through date1 and the next 6 days.
I cannot have a search which contains two date inputs because my users are so used to this way and i do not want to increase searching time. I started to think that I had to find the dates between the dates, add that to an array then use an if statement to find matches...but even saying this makes no sense to me.
regarding job 1, I need my calender to show this job up on all dates 28/29/30/31/01/02/03.
My current search SELECT * FROM jobs WHERE date1='$searchinput' PER day and calender this search. I use strtotime to increase the input date by +1 to add to the search for each day.
Calender page.
What I want with my results. User searched Date 28th.
Mon 28 | Tues 29 | Wed 30 ...... | Fri 03 |
_________________________________________________________________________
Job no 1 | job no 1 | job no 1 ...... | job no 1
What I have now.
Mon 28 | Tues 29 | Wed 30 ...... | Fri 03 |
_________________________________________________________________________
Job no 1 | blank | blank | job no 1
each day has a new select query right now. It matches days with date 1 and date 2. I dont need this as before I only had jobs out on one day now they go out for more than one day and need the job to be noted on all days it is out by only using a job from date and job to date.
EDIT 2:
SELECT * FROM calender_db NATURAL JOIN job_db
WHERE section='two'
AND date1 < '$day' AND date2 > '$day'
OR date1 = '$day' OR date2 = '$day'
This query selects what I need, but as I am using OR the first WHERE CLAUSE can be null. I need that to always be in the clause. I have been looking at using IIF or CASE to rectify but do not how to implement 100%...?
why not use BETWEEN
SELECT * FROM tableName WHERE date BETWEEN 'date1' AND 'date2'
SQLFiddle Demo
UPDATE 1
SELECT *
FROM tableName
WHERE date BETWEEN '2013-01-28' AND '2013-01-28' + INTERVAL 6 DAY
SQLFiddle Demo
To generate a list of days between two dates:
$days = array();
$stop = strtotime($date2);
for ($current = strtotime($date1); $current <= $stop; $current = strtotime('+1 days', $current)) {
$days[] = date('d', $current);
}
echo join('/', $days);
Demo
Update
Misunderstood the question it seems, if both dates are stored as columns and you're querying with a single date:
SELECT *
FROM jobs
WHERE 'date_from_input' BETWEEN date1 AND date2
Update 2
Your latest query can be written as:
SELECT *
FROM calender_db NATURAL JOIN job_db
WHERE section='two' AND '$day' BETWEEN date1 AND date2
Try like this
SELECT * FROM Mytimetable WHERE date BETWEEN 'date1' AND 'date2'
Query between date1 - date2
SELECT *
FROM `objects`
WHERE (date_field BETWEEN '2013-01-30 14:15:55' AND '2013-02-19 10:15:55')
OR
SELECT *
FROM `objects`
WHERE (date_field BETWEEN date1 AND date2)
query to select dates between two dates with PHP variables.
i will explain with exapmle :
$date1 = "2013-02-19";
$date2 = "2013-02-25";
then sql query will be :
$query = " SELECT * FROM table_xyz where (date_item BETWEEN date('".$date1."') AND date('".$date2."')";
hope it solves your problem
SELECT
*
FROM
tablename
WHERE
date between '$date1' and '$date2'
order by
date
I'm trying to output a list of different itmes grouped by the date they were stored in the database (unix timestamp).
I'd need help with both MySQL (query) and PHP (output).
MySQL table
id | subject | time
1 | test1 | 1280278800
2 | test2 | 1280278800
3 | test3 | 1280365200
4 | test4 | 1280451600
5 | test5 | 1280451600
OUTPUT
Today
test5
test4
Yesterday
test3
July 28
test2
test1
I'd appreciate any help on this. Thanks!;-)
You can convert your unix timestamp to a date using DATE(FROM_UNIXTIME(time)). This will output something like 2010-07-30.
The following should group by the date.
SELECT id, subject, time, DATE(FROM_UNIXTIME(time)) AS date_column
GROUP BY date_column
Edit: Didn't read your question correctly.
For this I would just run a standard SELECT and ORDER BY time DESC.
Then do the grouping with PHP.
$lastDate = null;
foreach ($rows as $row) {
$date = date('Y-m-d', $row['time']);
$time = date('H:i', $row['time']);
if (is_null($lastDate) || $lastDate !== $date) {
echo "<h2>{$date}</h2>";
}
echo "{$time}<br />";
$lastDate = $date;
}
you could create a mysql udf for that, something like this:
DELIMITER $$
DROP FUNCTION IF EXISTS `niceDate` $$
CREATE FUNCTION `niceDate` (ts INT) RETURNS VARCHAR(255) NO SQL
BEGIN
declare dt DATETIME;
declare ret VARCHAR(255);
set dt = FROM_UNIXTIME(ts);
IF DATE_FORMAT(dt, "%Y%m%d") = DATE_FORMAT(NOW(), "%Y%m%d") THEN SET ret = 'Today';
ELSEIF DATE_FORMAT(dt, "%Y%m%d") = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL -1 DAY), "%Y%m%d") THEN SET ret = 'Yesterday';
ELSE SET ret = CONCAT(DATE_FORMAT(dt, "%M "), DATE_FORMAT(dt, "%d"));
END IF;
RETURN ret;
END $$
DELIMITER ;
You could then construct your query like this:
select niceDate(your_date_field) from table group by niceDate(your_date_field) order by your_date_field desc
disclaimer: i haven't tested this function, but you should get the idea.
The easiest way is probably to sort by timestamp (descending) in SQL, and do the grouping in PHP: Iterate over the result set, converting the timestamp to a DateTime object; when the current date is on a different day than the previous one (hint: use DateTime::format()), insert a sub-heading.