I need to search a row between 2 times in one day
for example
current time is 13.30 O'clock
The first time is 13.00 O'clock
The second time is 14.00 O'clock
If the current time is between the first time and the second time, return true, else return false
i make some code like this :
$today = date("Y-m-d");
$this->db->query("select date, in, out from absent where date='$today' and id_user='120'")->result();
/*
the result is 3 rows
2019-3-7, 13:00, 14:00
2019-3-7, 09.00, 12.00
2019-3-7, 15:00, 17:00
*/
I just need one row which the current time is between the first and second time
Like this (if you have a single date time field):
$firstTime = (new DateTime)->format('H:i:s');
$secondTime = (new DateTime)->modify('+1 hours +2 minutes +3 seconds')->format('H:i:s');
$this->db->query("SELECT `date`, in, out FROM absent WHERE TIME(`date`) >= '$firstTime' AND TIME(`date`) <= '$secondTime' AND id_user='120'");
Date is a reserved word in MySQL so you have to escape it. You can do this for any part of a datetime field, MONTH(), DAY(), YEAR(), TIME(), HOUR() etc..
Then you just match your date format in this case just the time H:i:s and a bit of logic.
It's not clear but you may need something like this as it looks like you have a date field and two fields with Hour and Minutes?
$today = new DateTime;
$date = $today->format('Y-m-d');
$in = $today->format('H:i');
$out = $today->modify('+2 hours')->format('H:i');
$this->db->query("SELECT `date`, in, out FROM absent WHERE `date` = '$date' AND in >= '$in' AND out <= '$out' AND id_user='120'");
Personally in this case I would make in and out be full datetime fields, then you can use the date functions like above, and you can eliminate one column, and handle in and out values that bridge a date.
You can use below code:
$this->db->select('date, in, out');
$this->db->from('absent');
$this->db->where('date', $today);
$this->db->where('user_id', '120');
$this->db->where('in >='. $currentTime);
$this->db->where('out <='. $currentTime);
return $this->db->get()->result_array();
Hope it helps you.
Try like this
First, convert all three times into strtotime()
Second, result() will always give you more than one row if it will retrieve. Use row() to get only one record
$current = strtotime('time-one');
$first_time = strtotime('time-two');
$second_time = strtotime('time-three');
$date = date('Y-m-d');
Query
$this->db->select('*');
$this->db->from('table');
$this->db->where('date', $date);
$this->db->where('user_id', '120');
$this->db->where('time >='. $first_time);
$this->db->where('time <='. $second_time);
return $this->db->get()->row();
Related
So I have a database entry that update the date/time in yyyy-mm-dd hh:mm:ss.
Now I want to check, if there is a space inbetween the the database and the actual time from 60 minutes. How can I do that?
Example:
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 11:01:00
Do something
DB: 2020-02-14 10:00:00
Time now: 2020-02-14 10:59:00
Do nothing
You can use something like this:
$t1 = strtotime( '2006-04-14 11:30:00' );
$t2 = strtotime( '2006-04-12 12:30:00' );
$diff = round(($t1 - $t2) / 3600);
In MySQL, you can do date arithmetics:
update mytable
set mydatetime = now()
where mydatetime <= now() - interval 1 hour and id = ?
The where clause filters on record whose column mydatetimeis more than one hour old. You did not tell what you want to do , so I assumed an update query, that resets the date/time to the current date/time.
This assumes that you want to update the timestamp of a given record, not accross the whole table, hence condition id = ?, which you can adapt - or remove - for your use case.
Hello Schmaniel at first i think you should use Carbon()
https://carbon.nesbot.com/docs/ to get the right results. It's a great way to work with timeformats and timestamps.
$now = Carbon::now();
$dbtime = Carbon::createFromFormat('Y-m-d H:i:s', '1975-05-21 22:10:22');
$totalDuration = $now->diffForHumans($dbtime);
dd($totalDuration);
$currentDate = new DateTime();
$databaseDate = new DateTime($dateFromDatabase);
$interval = $datetime1->diff($datetime2);
Then you can check using the $interval variable
You can use mysql TIMESTAMPDIFF like this:
SELECT TIMESTAMPDIFF(HOUR,'2003-02-01','2003-05-01 12:05:55');
you can use one of the follwing units:
MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,
QUARTER, or YEAR.
How to apply date range filters to get rows of exact date
Below is my sql table
id name created
1 abc 2018-07-06 10:30:45
2 test 2018-07-01 10:30:45
3 raj 2018-07-05 10:30:45
4 zyz 2018-07-08 10:30:45
But when i select date 2018/07/01 - 2018/07/01 it returns empty rows,
and when i select date 2018/07/01 - 2018/07/02 then it will shows below single row
2 test 2018-07-01 10:30:45
My query is, how to apply date filter if i need record of selected date in from and to date range filter
Below is my php code
public function clientReport(){
if ($this->request->is('post')) {
$daterng = $this->request->data['daterange'];
if(!empty($daterng)){
$dates = explode("-", $daterng);
$frmDate = date("Y-m-d", strtotime($dates[0]));
$toDate = date("Y-m-d", strtotime($dates[1]));
}
$conditions = [];
if(!empty($frmDate)){
$conditions['Orders.created >='] = $frmDate;
}
if(!empty($toDate)){
$conditions['Orders.created <='] = $toDate;
}
$orders = $order
->find()
->where($conditions);
$orders->enableHydration(false); // You can retrieve basic arrays by disabling hydration
if(!empty($orders)){
$this->set('clientlist', $orders);
}
}
}
You have to add time also in query
if(!empty($frmDate)){
$conditions['Orders.created >='] = $frmDate.' 00:00:00';
}
if(!empty($toDate)){
$conditions['Orders.created <='] = $toDate.' 23:59:59';
}
You need to "round up" the end date to 23:59:59 hours. You're actually working with timestamps, so a date will be converted to a date/time. 2018/07/01 probably becomes midnight 00:00:00 on that day. When searching from 2018/07/01 to 2018/07/01, what you actually want is to search from 2018/07/01 00:00:00 to 2018/07/01 23:59:59.
To filter your data base on a date range you can use this
SELECT * FROM your_table WHERE DATE(created) BETWEEN '2018-07-01' AND '2018-07-01'
I'm trying to hide an event two days after it's passed in php (using a mysql query). There are two date options. Start date, and End date. I can't seem to figure out how to make the query work.
$query->select('*');
$query->from('#__events_items');
$query->where('date2 >= "'.$today.'"');
$query->where('date2 <= "'.$sixmths.'"');
$query->where('state = 1');
$query->order('date1 asc');
I've tried
$today = #date('Y-m-d');
$enddate = #date('Y-m-d',(strtotime(#date('Y-m-d')."+ 2 days")));
But obviously the end date won't be greater or equal to $enddate.. Any help would be greatly appreciated!
You can either modify today like so:
$today = date('Y-m-d', strtotime('-2 days'));
Or modify your query like so :
$query->select('*');
$query->from('#__events_items');
$query->where('date2 >= "'.$today.'" - INTERVAL 2 DAY');
$query->where('date2 <= "'.$sixmths.'"');
$query->where('state = 1');
$query->order('date1 asc');
I would say the second is probably better form since having $today represent two days ago would be nasty self documenting code.
I'm trying to count the rows with a datetime less that 10 minutes ago but the current time its being compared to seems to be 1 hour ahead so Imm getting 0 results, if I go into my table and put some fields forward an hour then I get results.
Getting results:
$stmt = $db->query('SELECT check_log FROM members WHERE check_log >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)');
$row_count = $stmt->rowCount();
echo $row_count.' Members online.';
The datetime of the field of of typing this is 2013-07-11 16:54:12 and I'm getting no results but if I manually change the date time to 2013-07-11 17:54:12 I get 1 result the datetime was input seconds ago using:
$date = date("Y-m-d H:i:s");
The 17:54:12 is my local time and 16:54:12 seem to be my servers time, is my compare trying to look into the future or is it using my local time as a reference?
PHP and MySQL don't agree on the current timezone.
Pass the desired time in as a literal from PHP to SQL instead of using NOW().
Always store date times in php's timezone.
One function you can particularly make use of is strtotime.
$now = strtotime("now"); // current timestamp
$hour_later = strtotime("+1 hour"); // hour later
$now = date("Y-m-d H:i:s", $now);
$hour_later = date("Y-m-d H:i:s", $hour_later);
I have a function that is accepting the date and time, and number of occurrences of an episode. I'm using a while loop to try and insert and episode every week on the same day and time. For example if the episode is monday at 7PM, i want to insert in for every monday at 7PM for the number of occurrences given.
Here's my code and while loop:
$sEpsAirDate = strtotime($aVars['air_date'].' '.$aVars['air_time'].$aVars['air_ampm']);
$i = 1;
while ($i <= $aVars['repeat_count']) {
$sEpsAirDate = // How can I alter this variable to change the date to every week?
db_res(
"INSERT INTO `hm_episodes_main` SET
`show_id` = '{$aVars['show_id']}',
`title` = '{$sEpsTitle}.{$i}',
`season` = '{$aVars['eps_season']}',
`uri` = '{$sUri}.{$i}',
`desc` = '{$sEpsDesc}',
`air_date` = '{$sEpsAirDate}'
");
$i++
}
How would I alter the $sEpsAirDate variable to be entered accurately on every day of the week on the given time?
Use mktime():
$next_ep_timestamp = mktime ($hour,$min,$sec, $first_ep_month, $first_ep_day + 7 * $weekcount, $first_ep_year);
"Init" this by setting the respective variables for the date, month and year of the first episode, then you can create new dates for following weeks by adding increments of 7 to the day-parameter in mktime (like shown above).
Then format for output to SQL like this:
$datetime_str = date("Y-m-d H:i:s", $next_ep_timestamp);
//gives a date-str like '2011-10-16 12:59:01'
The first idea that comes to my mind is just adding the seconds in a week to the sEpsAirDate with every iteration in the loop:
$sEpsAirDate += 604800;
If you needed to preserve the first air date you could copy it out into a separate variable and then do something like this (change the LCV $i to start at 0):
$sEpsAirDate = $sEpsFirstAirDate+(604800*$i);
But this method has the potential to create problems with Daylight Savings Time... so it might be safer to break the date into year, month and day variables and then recreate the $sEpsAirDate with every loop iteration by adding ($i*7) to day. ... So something like (again change the LCV $i to start at 0):
$sEpsAirDate = mktime($sEpsAirDateHour, $sEpsAirDateMinute, 0, $sEpsAirDateMonth, $sEpsAirDateDay+($i*7), $sEpsAirDateYear);