How to set fix time variables in php? - php

I want to set a fix time variables in php for my if and else condition.
For example:
$startTime = '08:00:00';
$endTime = '16:00:00';
$totalhrs = $endTime - $startTime;
echo $totalhrs;
Anyone know how to declare the time in PHP?
Thanks for the help

$startTime = strtotime('08:00:00');
$endTime = strtotime('16:00:00');
$totalhrs = ($endTime - $startTime) / 3600;
echo $totalhrs;

you can use datetime object for this case
$startTime = new DateTime('08:00:00');
$endTime = new DateTime('16:00:00');
$totalhrs = $startTime->diff($endTime)->h;

You can try the below function to check timestamps. If you don't pass it a second parameter, it will evaluate if the first time has passed the CURRENT time, otherwise it will compare the first time against the second.
Function timeHasPassed($Time, $Time2 = 0) {
If ($Time2 != 0) {
$Now = new DateTime($Time2);
} Else {
$Now = new DateTime();
}
$Then = new DateTime($Time);
If ($Now > $Then) {
Return TRUE;
} Else {
Return FALSE;
/*
You can also use the below code to print out how long is left until the timestamp has passed. Keep in mind, this will return TRUE if tested as a boolean so maybe consider returning a different datatype instead of TRUE if you decide to go this route.
$Time = new DateTime($Time);
$Now = new DateTime();
$Remainder = $Time->diff($Now);
$Remainder = $Remainder->format("%h hours, %i minutes, and %s seconds!");
return $Remainder;
*/
}
}

Related

How to add different timestamp

I'm having a problem adding two(2) timestamp for example:
00:30:00
00:45:31
========
01:15:31
I can't figure it out how to do it using laravel with carbon...
You can't add time like they are integer. One of the way is to convert it to another format and then add it. After adding them, convert it back to time type.
For example, try this:
$time1 = "00:30:00";
$time2 = "00:45:31";
$secs = strtotime($time2) - strtotime("00:00:00");
$result = date("H:i:s", strtotime($time1) + $secs);
dd($result); // "01:15:31"
My practice is to make TimeHelper class where I declare all my static methods that are related with calculations of time.
So basically I would make static function like this in TimeHelper class:
public static function addTwoTimes($time1 = "00:00:00", $time2 = "00:00:00"){
$time2_arr = [];
$time1 = $time1;
$time2_arr = explode(":", $time2);
//Hour
if(isset($time2_arr[0]) && $time2_arr[0] != ""){
$time1 = $time1." +".$time2_arr[0]." hours";
$time1 = date("H:i:s", strtotime($time1));
}
//Minutes
if(isset($time2_arr[1]) && $time2_arr[1] != ""){
$time1 = $time1." +".$time2_arr[1]." minutes";
$time1 = date("H:i:s", strtotime($time1));
}
//Seconds
if(isset($time2_arr[2]) && $time2_arr[2] != ""){
$time1 = $time1." +".$time2_arr[2]." seconds";
$time1 = date("H:i:s", strtotime($time1));
}
return date("H:i:s", strtotime($time1));
}
So wherever you need to sum two times just call TimeHelper::addTwoTimes(arg1, arg2);
I took example function from user Cha from this topic: PHP add up two time variables
This how you can achieve adding two times with a Carbon date. The explanation is shown in inline comments
$time1 = '00:30:00';
$time2 = '00:45:31';
// Use the first time to crate a new Carbon date
$baseDate = Carbon::parse($time1);
// Deconstruct the second time into hours, minutes and seconds
list($addHour, $addMinutes, $addSeconds) = explode(':', $time2);
// Add the hours, minutes and seconds to the Carbon object
$baseDate->addHours($addHour)->addMinutes($addMinutes)->addSeconds($addSeconds);
// Print the result: 00:30:00 + 00:45:31 = 01:15:31
echo "{$time1} + {$time2} = " . $baseDate->toTimeString();
You can use CarbonInterval class from Carbon library:
$durations = [
'00:30:00',
'00:45:31',
];
function getDuration($string)
{
[$hours, $minutes, $seconds] = explode(':', $string);
return CarbonInterval::hours($hours)->minutes($minutes)->seconds($seconds);
}
$total = getDuration(array_shift($durations));
foreach ($durations as $duration) {
$total->add(getDuration($duration));
}
echo $total->cascade()->format('%h:%i:%s'); // 1:15:31

php carbon check if now is between two times (10pm-8am)

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);

How can I check if a given date is newer than 3 days?

I have a date
2016-09-16
How can I check that if that date is less than 3 days old?
I'm being really stupid and the frustration is making me not figure it out
Here's my code
public function isNew()
{
return strtotime($this->created_at) > time() && strtotime($this->created_at) < strtotime('+3 days',time());
}
Should be easy to use DateTime and DateInterval to handle this.
$date = new DateTime('2016-09-16');
$diff = (new DateTime)->diff($date)->days;
return $diff < 3;
Using PHP's DateTime and DateInterval Classes would do you much good. Here's how:
<?php
function isNewerThan3Days($date) {
$today = new DateTime();
$date = new DateTime($date);
$diff = $today->diff($date);
$diffD = $diff->days;
if($diffD>=3){
return false;
}
return true;
}
var_dump(isNewerThan3Days("2016-09-14")); //<== YIELDS:: boolean true
Use diff(). It will return a DateInterval object. Within that object will be a days property (days) that you can access.
// compare two distinct dates:
$datetime1 = new DateTime('2016-09-16');
$datetime2 = new DateTime('2016-09-12');
$interval = $datetime1->diff($datetime2);
$daysOld = $interval->days;
// int(4)
// or compare today vs your date...
$datetime1 = new DateTime('2016-09-16');
$now = new DateTime();
$interval = $now->diff($datetime1);
$daysOld = $interval->days;
// int(0)
// then determine if it's at least 3 days old:
$is3daysOld = ($daysOld >= 3 ? true : false);
http://php.net/manual/en/datetime.diff.php
This should do it for you.
$date = new DateTime('2015-09-16');
$now = new DateTime();
$interval = $date->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
// $date is fewer than 3 days ago
}
In your isNew() method:
public function isNew() {
$created_at = new DateTime($this->created_at);
$now = new DateTime();
$interval = $created_at->diff($now);
$difference = $interval->format('%a');
if($difference < 3) {
return true;
}
return false;
}
return $this->created_at->diffInDays() < 3;
Without parameter diffInDays() will return the number of complete days between created_at and now.
Why don't you use Carbon ?
You can easily do that and many more in carbon like so :
$dt = Carbon::createFromDate(2011, 8, 1);
echo $dt->subDays(5)->diffForHumans(); // 5 days before

PHP timestamp and dates issue

So I have a piece of code on a certain page of my site that does things with timestamps. Pretty much what it does is there is a UNIX timestamp that is placed in the database from each individual Purchase Order. Once a certain amount of time has passed and nothing has been done to that Purchase Order then an indication will begin flashing on the page with the amount of hours that is past due. Once someone takes action then the flashing indication goes away.
Now, everything is working perfectly fine. The issue I am having is that the indicator should only take Monday thru Friday into account. Not the weekends. Also, I've set the hours from 9am to 5pm est but the code seems to 100% skip all these restrictions and just takes all days and times into consideration.
I've placed the code below and as you can see I've set the restrictions of days and time but it seems to be voided somehow. Any help would be much appreciated with this issue.
$current_stardate = time();
$past_stardate = $stardate['time_stamp'];
$placer = ($current_stardate - $past_stardate) / 3600;
$from = date("Y-m-d H:i:s", $current_stardate);
$to = date("Y-m-d H:i:s", $past_stardate);
define('DAY_WORK', 28800); // 9 * 60 * 60
define('HOUR_START_DAY', '09:00:00');
define('HOUR_END_DAY', '17:00:00');
$date_begin = $to;
$date_end = $from;
$d1 = new DateTime($date_begin);
$d2 = new DateTime($date_end);
$period_start = new DateTime($d1->format('Y-m-d 00:00:00'));
$period_end = new DateTime($d2->format('Y-m-d 23:59:59'));
$interval = new DateInterval('P1D');
$period = new DatePeriod($period_start, $interval, $period_end);
$worked_time = 0;
$nb = 0;
foreach($period as $date){
$week_day = $date->format('w'); // 0 (for Sunday) through 6 (for Saturday)
if (!in_array($week_day,array(1, 5)))
{
if ($date->format('Y-m-d') == $d1->format('Y-m-d'))
{
$end_of_day_format = $date->format('Y-m-d '.HOUR_END_DAY);
$d1_format = $d1->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $end_of_day->diff($d1)->format("%H:%I:%S");
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else if ($date->format('Y-m-d') == $d2->format('Y-m-d'))
{
$start_of_day = new DateTime($date->format('Y-m-d '.HOUR_START_DAY));
$d2_format = $d2->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $start_of_day->diff($d2)->format('%H:%I:%S');
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else
{
$worked_time += DAY_WORK;
}
}
if ($nb> 10)
die("die ".$nb);
}
$the_work = $worked_time/60/60;
$genesis_stardate = strtotime($stardate['date_purchased']);
if($past_stardate == NULL)
{
$the_work = NULL;
$future_days = NULL;
}
else
{
$future_days = ($current_stardate - $past_stardate) / 3600;
}
$date is not defined. Try to define it, and the problem should be solved.

function's value in PHP DateTime?

okay, I am at my wits end with this. been trying to solve this for 3 days now and I am getting nowhere with this.
I need to get the value of $offset between two locations and take it off of a set time which is (00:00).
here is how I set the $offset value and it works just fine.
<?php
if( isset($_POST['submit']))
{
//be sure to validate and clean your variables
$timezone1 = htmlentities($_POST['timezone1']);
$timezone2 = htmlentities($_POST['timezone2']);
//then you can use them in a PHP function.
function get_timezone_offset( $origin_tz, $remote_tz ) {
$timezone1 = new DateTimeZone ( $origin_tz );
$timezone2 = new DateTimeZone ( $remote_tz );
$datetime1 = new DateTime ("now", $timezone1);
$datetime2 = new DateTime ("now", $timezone2);
$offset = $timezone1->getOffset($datetime1) - $timezone2->getOffset($datetime2);
return $offset;
}
$offset = get_timezone_offset($timezone1, $timezone2);
}
?>
And here is how I've tried to do what i want using DateTime, this code will only echo's the $offset value without taking it off of the 00:00
<?php
if (0 > $offset)
{
// set an object with the current date
$date = new DateTime();
$date->setTime(00, 00);
// the second date
$date2 = new DateTime($offset/3600 * 1);
// apply the diff() method, getting a DateInterval object ($diDiff)
$diDiff = $date->diff($date2) ;
}
echo $diDiff->format("%H:%i");
?>
And i even tried to use strtotime but strtotime returns a wrong value and i have been advised by some guys on stackoverflow to use DateTime.
<?php
$time1 = strtotime('00:00');
if (0 > $offset)
{
// For negative offset (hours behind)
$hour_dif = date('H:i', strtotime($time1 -$offset/3600));
$time1 = "{$hour_dif}";
}
elseif (0 < $offset)
{
// For positive offset (hours ahead)
$hour_dif = date('H:i', strtotime($time1 +$offset/3600));
$time1 = "{$hour_dif}";
}
else
{
// For offsets in the same timezone.
$time1 = "in the same timezone";
}
echo "{$time1}";
?>
Please someone help me out as it is absolutely killing my time.
You can also easily solve this using Carbon, a class that will greatly simplify doing date calculations of any kind:
// example timezones
$timezone1 = 'Europe/Berlin';
$timezone2 = 'Asia/Yakutsk';
$dt1 = Carbon::createFromDate(2000, 1, 1, $timezone1);
$dt2 = Carbon::createFromDate(2000, 1, 1, $timezone2);
// false will force a relative difference, so it can be a negative result
$difference = $dt1->diffInMinutes($dt2, false);
$dtMidnight = Carbon::create(2000, 1, 1, 12, 0, 0);
// get the difference from midnight
$differenceFromMidnight = $dtMidnight->addMinutes($difference);
echo $differenceFromMidnight->hour;
echo $differenceFromMidnight->minute;
This handles both positive and negative offsets:
$sign = $offset >= 0 ? 1 : -1;
$offset = $offset * $sign; // make sure offset is a positive number
// set an object with the current date
$date = new DateTime();
$date->setTime(00, 00);
// the second date
$date2 = new DateTime();
$interval = new DateInterval("PT" . $offset . "S");
if ($sign > 0) {
$date2->add($interval);
} else {
$date2->sub($interval);
}
echo $date2->format("H:i");
The following code will print the input time adjusted by $offset amount of hours.
$date = new DateTime();
$date->setTime(00, 00);
$date->add(DateInterval::createFromDateString("{$offset} hours"));
echo $date->format('H:i');
I have, again, tested this solution (with PHP 5.4.17) and it correctly shifts the time.
PHPFiddle: http://phpfiddle.org/main/code/rhd-pj4

Categories