php - check difference on dates + additional time - php

What would be a good way to check if point is between start and extra.
point = 2010-06-20
start = 2010-06-17
extra = start + "1 week"
Any ideas would be appreciate it.

take a look at strtotime - an then simply compare the resulting timestamps:
$start = strtotime('2010-06-20');
$point = strtotime('2010-06-17');
$extra = strtotime('+1 week', $start);
if($start < $point && $extra > $point){
// it's bewtween...
}

Requires PHP 5.3
$period = new DatePeriod(
new DateTime('2010-06-17'),
DateInterval::createFromDateString('+1 day'),
new DateTime('2010-06-17 +1 week')
);
if (in_array(new DateTime('2010-06-20'), iterator_to_array($period))) {
// date is in range
}
Manual http://de2.php.net/manual/en/dateperiod.construct.php
I'd probably extend the DatePeriod class to have a contains methods:
class DateRange extends DatePeriod
{
public function contains(DateTime $dateTime)
{
return in_array($dateTime, iterator_to_array($this));
}
}
then you can do
$period = new DateRange(
new DateTime('2010-06-17'),
DateInterval::createFromDateString('+1 day'),
new DateTime('2010-06-17 +1 week')
);
if ($period->contains(new DateTime('2011-06-20'))) {
// date is in range
}

try this
$start_timestamp = strtotime('2010-05-17');
$end_timestamp = strtotime(date("Y-m-d", $start_timestamp) . " +1 week");
$point_timestamp = strtotime('2010-16-20');
if ($point_timestamp < $end_timestamp && $point_timestamp > $point_timestamp) {
// Do your work
}

Related

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

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

How to iterate day in php?

I need to get the next 7 (or more) dates except sunday. Firstly i did it like
$end_date = new DateTime();
$end_date->add(new DateInterval('P7D'));
$period = new DatePeriod(
new DateTime(),
new DateInterval('P1D'),
$end_date
);
And after checked $period in foreach. But then i noticed that if i remove Sunday i need to add one more day to the end and this is each time when Sunday is... Is there any way to do it?
$start = new DateTime('');
$end = new DateTime('+7 days');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
if ($dt->format("N") === 7) {
$end->add(new DateInterval('P1D'));
}
else {
echo $dt->format("l Y-m-d") . PHP_EOL;
}
}
See it in action
I'm a fan of using iterators, to keep the actual loop as simple as possible.
$days_wanted = 7;
$base_period = new DatePeriod(
new DateTime(),
new DateInterval('P1D'),
ceil($days_wanted * (8 / 7)) // Enough recurrences to exclude Sundays
);
// PHP >= 5.4.0 (lower versions can have their own FilterIterator here)
$no_sundays = new CallbackFilterIterator(
new IteratorIterator($base_period),
function ($date) {
return $date->format('D') !== 'Sun';
}
);
$period_without_sundays = new LimitIterator($no_sundays, 0, $days_wanted);
foreach ($period_without_sundays as $day) {
echo $day->format('D Y-m-d') . PHP_EOL;
}
You cannot remove days from a DatePeriod, but you can simply keep a count of non-Sundays and keep iterating until you have accumulated 7 of them:
$date = new DateTime();
for ($days = 0; $days < 7; $date->modify('+1 day')) {
if ($date->format('w') == 0) {
// it's a Sunday, skip it
continue;
}
++$days;
echo $date->format('Y-m-d')."\n";
}
You can try using UNIX time, adding day and if day is Sunday, add another one.
First day of your list will be eg. today at 12:00. Than you add 24 * 60 * 60 to get next day, and so on. Convert UNIX to day is simple, use date() function.
$actDay = time();
$daysCount = 0;
while(true)
{
if (date("D", $actDay) != "Sun")
{
//do something with day
$daysCount++;
}
if ($daysCount >= LIMIT) break;
$actDay += 24 * 60 * 60;
}

Get date range between two dates excluding weekends

Given the following dates:
6/30/2010 - 7/6/2010
and a static variable:
$h = 7.5
I need to create an array like:
Array ( [2010-06-30] => 7.5 [2010-07-01] => 7.5 => [2010-07-02] => 7.5 => [2010-07-05] => 7.5 => [2010-07-06] => 7.5)
Weekend days excluded.
No, it's not homework...for some reason I just can't think straight today.
For PHP >= 5.3.0, use the DatePeriod class. It's unfortunately barely documented.
$start = new DateTime('6/30/2010');
$end = new DateTime('7/6/2010');
$oneday = new DateInterval("P1D");
$days = array();
$data = "7.5";
/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $data;
}
}
print_r($days);
The simplest method:
$start = strtotime('6/30/2010');
$end = strtotime('7/6/2010');
$result = array();
while ($start <= $end) {
if (date('N', $start) <= 5) {
$current = date('m/d/Y', $start);
$result[$current] = 7.5;
}
$start += 86400;
}
print_r($result);
UPDATE: Forgot to skip weekends. This should work now.
This is gnud's answer but as a function (also added an option to exclude the current day from the calculation):
(examples below)
public function getNumberOfDays($startDate, $endDate, $hoursPerDay="7.5", $excludeToday=true)
{
// d/m/Y
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$oneday = new DateInterval("P1D");
$days = array();
/* Iterate from $start up to $end+1 day, one day in each iteration.
We add one day to the $end date, because the DatePeriod only iterates up to,
not including, the end date. */
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = $hoursPerDay;
}
}
if ($excludeToday)
array_pop ($days);
return $days;
}
And to use it:
$date1 = "2012-01-12";
$date2 = date('Y-m-d'); //today's date
$daysArray = getNumberOfDays($date1, $date2);
echo 'hours: ' . array_sum($daysArray);
echo 'days: ' . count($daysArray);
This is OOP approach, just in case. It returns an array with all of dates, except the weekends days.
class Date{
public function getIntervalBetweenTwoDates($startDate, $endDate){
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
new DateTime($endDate)
);
$all_days = array();$i = 0;
foreach($period as $date) {
if ($this->isWeekend($date->format('Y-m-d'))){
$all_days[$i] = $date->format('Y-m-d');
$i++;
}
}
return $all_days;
}
public function isWeekend($date) {
$weekDay = date('w', strtotime($date));
if (($weekDay == 0 || $weekDay == 6)){
return false;
}else{
return true;
}
}
}
$d = new Date();
var_dump($d->getIntervalBetweenTwoDates('2015-08-01','2015-08-08'));

Categories