I want to know how do I use php to ask if time is bigger than
08:30
and lower than
21:15
if I use :
<?php
if ( (date("H")>8&&date("i")>30) && (date("H")<21&&date("i")<25) ) {
echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
exit;
}
?>
This is not an accurate way to say that because even if time is bigger than 8 and lower than 21 there is a minute validation here...
You could get the date/time and strip of the date part. That time can be compared to other time values. In the code below, I calculate the values in seconds from midnight for the current time, 8:30 and 21:15, and then the if becomes quite simple:
define('SecondsPerDay', 86400);
define('SecondsPerHour', 3600);
define('SecondsPerMinute', 60);
$time = time () % SecondsPerDay;
$from = 8 * SecondsPerHour + 30 * SecondsPerMinute;
$to = 21 * SecondsPerHour + 15 * SecondsPerMinute;
if ($time >= $from && $time < $to) {
echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
exit;
}
$startTime = '08:30';
$endTime = '21:15';
$time = new DateTime($startTime);
$time1 = date_format($time, 'H:i');
$time = new DateTime($endTime);
$time2 = date_format($time, 'H:i');
"Today is " . $current =date("H:i") . "<br>";
if ($current > $time1 && $current < $time2)
{
echo 'This website is closed from 08:30 - 21:25. Sorry for the Inconvenience.';
}else{
echo "It's open";
}
REFERENCE
Related
This question already has answers here:
How do I find the hour difference between two dates in PHP?
(10 answers)
Closed 5 years ago.
I have datetimes in the following format:
Start: 2017-07-16 20:00
End: 2017-07-16 23:30
Start: 2017-07-18 21:30
End: 2017-07-19 00:30
I need to tell from these intervals how many hours (in 0,5 increments) are spent between 18:00-22:00 and 22:00-06:00 in total for a month.
Thanks in advance for any hint.
The current code I have is this, but I'm not sure if it is covering all timeframe possibilities:
<?php
date_default_timezone_set("UTC");
$start = array(
"2017-07-16 21:30:00",
"2017-07-16 18:00:00"
);
$end = array(
"2017-07-17 00:30:00",
"2017-07-16 18:30:00"
);
$amount_low = 0;
$amount_high = 0;
for($i = 0; $i < sizeof($start); $i++) {
$start_time = date("H:i:s", strtotime($start[$i]));
$end_time = date("H:i:s", strtotime($end[$i]));
$start_date = date("Ymd", strtotime($start[$i]));
$end_date = date("Ymd", strtotime($end[$i]));
// getting chunk before 22:00 if
if(
(strtotime($start[$i]) >= strtotime($start_date . " 18:00") && strtotime($start[$i]) < strtotime($start_date . " 22:00"))
&&
$start_date < $end_date
) {
$interval_low = strtotime($start_date . " 22:00") - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
//amount_high
if(strtotime($start[$i]) > strtotime($start_date . " 22:00") && strtotime($start[$i]) < strtotime($start_date . " 06:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start[$i]); //needs further things
$amount_high += ceil($interval_high / 1800) / 2;
} elseif (strtotime($start[$i]) < strtotime($start_date . " 22:00") && strtotime($end[$i]) > strtotime($start_date . " 22:00")) {
$interval_high = strtotime($end[$i]) - strtotime($start_date . " 22:00");
$amount_high += ceil($interval_high / 1800) / 2;
} else {
$interval_low = strtotime($end[$i]) - strtotime($start[$i]);
$amount_low += ceil($interval_low / 1800) / 2;
}
}
echo $amount_low;
echo "\n$amount_high";
?>
Would this work for you?
$start = strtotime('2017-07-16 20:00');
$end = strtotime('2017-07-16 23:30');
$interval = $end - $start;
$hours = floor($interval / 1800)/2;
echo($hours);
This will display the total hours (in 0,5 increments) between the two dates (rounding down, so if it's 55 minutes, it's 0,5 hours; replace 'floor' with 'ceil' for the opposite).
I believe a part of your solution is found here from Aillyn
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round()
to avoid having a lot of decimal places.
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
This will give you a rounded hour difference between the two times. You could do something similar, just apply it for each interval for which ever month and adjust your math. There's not really going to be a single PHP function you can call to solve this.
I have a code where it will subtract the Total Duration and the Total Time, and after that the result for the computation will be converted into seconds...
Assuming in my Total Duration is "02:00:00"
then for Total Time is "01:30:00"
For computation...
02:00:00 - 01:30:00 = 00:30:00
then for the result, "00:30:00" will be converted to seconds and the result is "1800"
How can I convert it?
Thanks for the help...
Use strtotime function. It returns the UNIX timestamp (number of seconds since January 1st 1970 00:00:00). If you'll pass the hour format HH:MM:SS to it, you can easily do the math
$to = strtotime('02:00:00');
$from = strtotime('01:30:00');
$seconds = $to - $from; // outputs 30
You assumed that the format is minutes:seconds:miliseconds and you wanted to receive 30 seconds in your case. Actually the output is 30 minutes. Miliseconds are separated with a dot.
Your hours should probably look like this:
$to = strtotime('00:02:00');
$from = strtotime('00:01:30');
How about splitting the Time-String into three substrings with the function (returns an array of substrings)
$substrings = new Array();
$substrings = explode(":", $timeString);
Now the array $substrings contains three substrings (hours, minutes, seconds).
you could compute the seconds just by multiplicating:
$hours = intval($substrings[0]);
$minutes = intval($substrings[1]);
$seconds = intval($substrings[2]);
$seconds = $hours * 3600 + $minutes * 60 + $seconds;
Can you try this,
$start = '01:30:00';
$end = '02:00:00';
$workingHours = (strtotime($end) - strtotime($start));
$res= date("i", $workingHours);
echo "DIFF: ". $res; //OP 30 Minutes
echo $resFull= date("H:i:s", $workingHours); //OP 00:30:00
If you use format HH:MM:SS then you can convert it to seconds by next code
$timestr = "00:30:00";
$temp = explode(":", $timestr);
if ($temp && is_array($temp) && count($temp) == 3) {
$time = intval($temp[0]) * 3600 + intval($temp[1]) * 60 + intval($temp[1]);
} else {
$time = null;
}
Alternative with PHP 5.3:
<?php
try {
$date1 = new DateTime('02:00:00');
$date2 = new DateTime('01:30:00');
$diff = $date1->diff($date2);
echo $diff->format('H:i:s');
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
i have lets say a $value = 5; and the valnue means 5 minutes, and i have a file saved on the server and getting modified a lot called check.txt i want a code to do a calculation of if timenow - timemodification of file <= 0 in H:i:s from the main $value of 5 minutes then continue, else echo please wait minutes left from the time now - filetimemodification of the main value of 5 minutes = $timeleft in m:s format.
i'm testing on the current code but i keep getting a value of -1376352747
my code which is know is bad :) is
$filename = 'check.txt';
$time = date("H:i:s");
$time = str_replace("00", "24", $time);
$filemodtime = filemtime($filename);
$timeleft = $time - $filemodtime;
$h = explode(':', $time);
$h = $h[0];
$h = str_replace("00", "24", $h);
$m = explode(':', $time);
$m = $m[1];
$s = explode(':', $time);
$s = $s[2];
$hms = ("$h:$m:$s");
if (count($filemodtime - $time) <= 0) {
echo "you can continue";
}
else {
echo " please wait $timeleft";
}
thanks in advance
The filemtime() function returns a UNIX-timestamp in seconds, and the time() function returns the current time as a UNIX-timestamp. So by using that difference, you get the file's age in seconds.
$age = time() - filemtime($filename);
// if older then 5 minutes (5 * 60 secounds)
if($age > $value*60)
{
// good
}
else
{
$time_left = $value * 60 - $age;
$time_left_secounds = $time_left % 60;
$time_left_minutes = ($time_left - $time_left_secounds) / 60;
$formated_time_left = sprintf("%02d:%02d", $time_left_minutes, $time_left_secounds);
echo "Please wait {$formated_time_left}";
}
I would recommend to work with time() rather than date().
that way, you can substract the file time from the current time() function, and see if it is bigger than 5 minutes * 60 seconds.
Good luck!
I'm working with a function I found to do this, but I'm trying to make it work with a GMT utc timestamp:
EDIT:
Maybe my issue is with how i'm "converting" the user input time to GMT...
I was doing
$the_user_input_date = strtotime('2011-07-20T01:13:00');
$utctime = gmdate('Y-m-d H:i:s',$the_user_input_date);
Does gmdate('Y-m-d H:i:s',$the_user_input_date); not actually "convert" it to gmt? does it just format it? Maybe thats my issue.
Here's what the times I can supply would look like:
//local time in GMT
2011-07-20T01:13:00
//future time in GMT
2011-07-20T19:49:39
I'm trying to get this to work like:
Started 36 mins ago
Will start in 33 mins
Will start in 6 hrs 21 mins
Will start in 4 days 4 hrs 33 mins
Here's what im working with so far:
EDIT: new php code im working with, seems to ADD 10 HOURS on to my date. Any ideas? I updated it here:
function ago($from)
{
$to = time();
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"year" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"week" => 604800, // seconds in a week (7 days)
"day" => 86400, // seconds in a day (24 hours)
"hour" => 3600, // seconds in an hour (60 minutes)
"minute" => 60, // seconds in a minute (60 seconds)
"second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(", "));
return $output;
}
#Jason
I tried what you suggested here:
function ago($dateto)
{
$datetime1 = new DateTime( $dateto);
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
// print_r($interval);
$format = '';
if ($interval->h) {
$format .= ' %h ' . ($interval->h == 1 ? 'hour' : 'hours');
}
if ($interval->i) {
$format .= ' %i ' . ($interval->i == 1 ? 'minute' : 'minutes');
}
// more logic for each interval
if ($format) {
echo $interval->format($format), ' ago';
}
else {
echo 'now';
}
}
It always seems to add 10 hours on to my time.
Any ideas what could be going on?
Maybe an error lies with how I'm saving the target time?
When someone submits a time its converted and stored like this
The user submitted time will always start out looking like this as their local time:
07/20/2011 11:00 pm
Then:
$time = mysql_real_escape_string($_POST['time']);
$the_date = strtotime($time);
//make user input time into GMT time
$utctime = gmdate('Y/m/d H:i:s',$the_date);
$query = "INSERT INTO $table (time) VALUES ('$utctime');";
mysql_query($query);
Provided you have access to PHP >= 5.3 I'd recommend DateTime::diff(). The DateInterval returned gives you all the parts you would need for display as well as has its own methods, such as format().
Here's a sample to give you an idea. There are more complete samples in the comments of the PHP documentation links.
<?php
$datetime1 = new DateTime('2011-07-20');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
// print_r($interval);
$format = '';
if ($interval->h) {
$format .= ' %h ' . ($interval->h == 1 ? 'hour' : 'hours');
}
if ($interval->i) {
$format .= ' %i ' . ($interval->i == 1 ? 'minute' : 'minutes');
}
// more logic for each interval
if ($format) {
echo $interval->format($format), ' ago';
}
else {
echo 'now';
}
It outputs (on my system):
22 hours 10 minutes ago
Your $datefrom is a string, but $dateto is an int. You can't subtract them that way.
Instead of:
$datefrom=gmdate("Y/m/d\TH:i:s\Z");
Do:
$datefrom=time();
PS. I did not check the rest of the code.
I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}