Run functions when current time is outside user metadata database times - php

I have a somewhat complicated time equation that had been driving me mental!
What I have so far is:
$current = time(); // UTC time
$user_in = '8:00 am'; // local time
$user_out = '4:00 pm'; // local time
$gmt_off = '11'; // Australia EST (+1 at the moment)
I then have the function that will convert the local time to UTC by subtracting the GMT offset, and output it as g:i a
function utc( $time ) {
$time = ( empty($time) ? null : strtotime($time) );
$gmt = '60 * 60 * 11'; // there is an actual check for it to be 10 or 11 - and in seconds
$out = ( $time - $gmt );
$out = date( 'Y-m-d g:i a', $out );
return $out;
}
What I cannot figure out is how to properly configure the conditions to check if the current time is outside the $user times
$user_in_utc = utc( $user_in );
$user_out_utc = utc( $user_out );
if( $current < $user_in_utc && $current > $user_out_utc ) {
// do something
}
However, the problem I'm running into is that say current time is 6:00pm local time.
How do I check it is now currently less than $user_out when it keeps saying the date is today and not tomorrow?
I intend for these functions to run if the statement being true as a cron task

Just use date_default_timezone_set and strtotime to get your timestamp values, and they will all be in the same timezone and hence directly comparable. Note that your condition should use || (or) rather than && (and) to check if the time is outside user hours.
date_default_timezone_set('Australia/Sydney');
$current = strtotime('now');
$user_in = strtotime('8:00 am');
$user_out = strtotime('4:00 pm');
if( $current < $user_in || $current > $user_out ) {
// do something
}

Related

Multiple Operators in PHP If Statement

Just wanted to double check and make sure my line of thinking is correct. This hook runs every 48 hours, so I need to check if an event is happening today or tomorrow.
$now = date('Y/m/d');
$today = explode("/", $now);
The event start date has the same format, but the value varies, and is stored the same way.
if ( $today[1] == $eventDate[1] &&
(intval($today[2]) == (intval($eventDate[2]-1)) || (intval($today[2]) == intval($eventDate[2])-2))) {
//run code
}
In my opinion, you should consider to work with DateTime objects :
$today = new \DateTime();
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);
if ($today->format('d-m-Y') === $eventDateTime->format('d-m-Y')) {
...
}
If you want to check that an event is happening today or tomorrow, you could do like this :
$start = new \DateTime();
$start->setTime(0,0,0);
$end = new \DateTime();
$end->add(new \DateInterval('P1D'));
$end->setTime(23,59,59);
$eventDateTime = \DateTime::createFromFormat('Y/m/d', $eventDate);
if ($eventDateTime >= $start && $eventDateTime <= $end) {
...
}
This way you check if a date is in a certain period. Here I added 1 day to the current date but you can adapt the code and set more than 1 day if you want.

php get time intervals between 2 times

I am trying to create a booking form where a user can select a booking time between 2 given times in 5 minute intervals. For example I want time slots between 10am and 12pm which would give me about 20 time slots.
When the user goes to select a slot, the earliest slot should be at least 15 mins ahead of the current time but the user can select a slot and hour or more if desired.
I found some code on SO (can't remember where) and I've edited it for my needs and it works if the current time is within the start and end time but if the current time is an hour before the earliest time, it doesn't create the time slots.
I know why it does it but i don't know how to fix it. It has to do with the while condition.
I would like to be able to book a slot hours before the first available slot if that is possible.
$timenow = time();
$start_time = strtotime('+15 minutes', $timenow);
// round to next 15 minutes (15 * 60 seconds)
$start_time = ceil($start_time / (5 * 60)) * (5 * 60);
//set the start times
$opentime = strtotime('10:00');
$closetime = strtotime('11:55');
// get a list of prebooked slots from database
$time_slots = $this->countStartTimes();
$available_slots = array();
while($start_time <= $closetime && $start_time >= $opentime) {
$key = date('H:i', $start_time);
if(array_key_exists($key, $time_slots)) {
if($time_slots[$key] == SLOTS) {
$available_slots[] = 'FULL';
break;
}
}
$available_slots[] = date('H:i', $start_time);
$start_time = strtotime('+5 minutes', $start_time);
}
I managed to get it working using Datetime()
$timenow = new DateTime(date('H:i'));
$timenow->add(new DateInterval('PT15M'));
$start = new DateTime('11:00');
$end = new DateTime('14:00');
$interval = new DateInterval('PT5M');
$time_slots = $this->countStartTimes();
$available_slots = array();
$period = new DatePeriod($start, $interval, $end);
foreach($period as $time) {
$timeslot = $time->format('H:i');
if ($timenow > $time) {
continue;
}
if(array_key_exists($timeslot, $time_slots)) {
if($time_slots[$timeslot] == SLOTS) {
$available_slots[] = array('key' => $timeslot, 'value' => 'FULL');
continue;
}
}
$available_slots[] = array('key' => $timeslot, 'value' => $timeslot);
}
Carbon has all of the functions inherited from the base DateTime class. This approach allows you to access the base functionality if you see anything missing in Carbon but is there in DateTime.
// Carbon::diffInYears(Carbon $dt = null, $abs = true)
echo Carbon::now('America/Vancouver')->diffInSeconds(Carbon::now('Europe/London')); // 0
$dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2000, 1, 1, 'America/Vancouver');
echo $dtOttawa->diffInHours($dtVancouver); // 3
echo $dtOttawa->diffInHours($dtVancouver, false); // 3
echo $dtVancouver->diffInHours($dtOttawa, false);
Use carbon class for this it really help you

Php date() not working

I am using wordpress as my cms..
i had need to schedule post programmatically every 60 seconds
This is the code i am using
function techento_data_valid_schedule($data) {
if ($data['post_type'] == 'post') {
if ($data['post_status'] == 'publish') {
// If post data is invalid then
$time += 60;
$data['post_status'] = 'future';
$data['post_date'] = date('Y-m-d H:i:s', $time);
$data->edit_date = true;
}
}
return $data;
}
add_filter( 'wp_insert_post_data', 'techento_data_valid_schedule', '99', 2 );
but when i publish the post...
it sets the date to jan 1. 1970 ?
Am unable to find the error in the codes ?
You're not setting your $time value anywhere, so when you get to the line $time += 60, you're getting $time = 0 + 60 which, in unixtime is Jan 1, 1970 at 00:01:00.
To correct this, you need to set your $time variable to whatever you need. If you want it to be the current time, try $time = time(); and then add 60 seconds.

Trouble calculating and displaying days left in PHP

I have two variables stored in my database containing the following data:
$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;
I want to show an advert for 15 days from the date it was published. To do so I need to work out the time difference.
I have read various places online about calculating time difference and have come up with the below code
In my attempt to work out the equation I can't seem to calculate the differences between $now - the date today, the $date_published and the $advert_duration. I can't get the correct result:
function days_left($date_published, $advert_duration){
$date = new DateTime($date_published);
$now = new DateTime();
$days_elapsed = $date->diff($now)->format("%d");
$days_left = $advert_duration - $days_elapsed;
return $days_left;
}
function getDaysLeft( $date, $duration )
{
// create $date and modify it by $duration
$date = new DateTime( $date );
$date->modify( sprintf( '+%d days', $duration ) );
// calculate the difference
$now = new DateTime();
$daysElapsed = (int) $now->diff( $date )->format( '%a' );
// set to negative value, if modified $date is before $now
if( $date < $now )
{
$daysElapsed = $daysElapsed * -1;
}
return $daysElapsed;
}
var_dump(
getDaysLeft( '2012-05-04 00:00:00', 15 ),
getDaysLeft( '2012-07-04 00:00:00', 15 )
);
If you're fetching your ad from the database, you can simply use a date function to calculate this :
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date
Or you can do this in PHP (you'll get an UNIX timestamp) :
$date = strtotime('+15 days', strtotime($date_published));

PHP Check if current time is before specified time

I need to check in PHP if the current time is before 2pm that day.
I've done this with strtotime on dates before, however this time it's with a time only, so obviously at 0.00 each day the time will reset, and the boolean will reset from false to true.
if (current_time < 2pm) {
// do this
}
if (date('H') < 14) {
$pre2pm = true;
}
For more information about the date function please see the PHP manual. I have used the following time formatter:
H = 24-hour format of an hour (00 to 23)
Try:
if(date("Hi") < "1400") {
}
See: http://php.net/manual/en/function.date.php
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
You could just pass in the time
if (time() < strtotime('2 pm')) {
//not yet 2 pm
}
Or pass in the date explicitly as well
if (time() < strtotime('2 pm ' . date('d-m-Y'))) {
//not yet 2 pm
}
Use 24 hour time to get round the problem like so:
$time = 1400;
$current_time = (int) date('Hi');
if($current_time < $time) {
// do stuff
}
So 2PM equates to 14:00 in 24 hour time. If we remove the colon from the time then we can evaluate it as an integer in our comparison.
For more information about the date function please see the PHP manual. I have used the following time formatters:
H = 24-hour format of an hour (00 to 23)
i = Minutes with leading zeros (00 to 59)
You haven't told us which version of PHP you're running, although, assuming it's PHP 5.2.2+ than you should be able do it like:
$now = new DateTime();
$twoPm = new DateTime();
$twoPm->setTime(14,0); // 2:00 PM
then just ask:
if ( $now < $twoPm ){ // such comparison exists in PHP >= 5.2.2
// do this
}
otherwise, if you're using one of older version (say, 5.0) this should do the trick (and is much simplier):
$now = time();
$twoPm = mktime(14); // first argument is HOUR
if ( $now < $twoPm ){
// do this
}
If you want to check whether the time is before 2.30 pm ,you can try the following code segment .
if (date('H') < 14.30) {
$pre2pm = true;
}else{
$pre2pm = false;
}
Try with
if( time() < mktime(14, 0, 0, date("n"), date("j"), date("Y")) ) {
// do this
}
This function will check if it's between hours in EST by accepting 2 params, arrays with the hour and am/pm...
/**
* Check if between hours array(12,'pm'), array(2,'pm')
*/
function is_between_hours($h1 = array(), $h2 = array())
{
date_default_timezone_set('US/Eastern');
$est_hour = date('H');
$h1 = ($h1[1] == 'am') ? $h1[0] : $h1[0]+12;
$h1 = ($h1 === 24) ? 12 : $h1;
$h2 = ($h2[1] == 'am') ? $h2[0] : $h2[0]+12;
$h2 = ($h2 === 24) ? 12 : $h2;
if ( $est_hour >= $h1 && $est_hour <= ($h2-1) )
return true;
return false;
}
Use time(), date() and strtotime() functions:
if(time() > strtotime(date('Y-m-d').' 14:00') {
//...
}

Categories