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
Related
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;
*/
}
}
$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);
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
Please bear with me as I try to explain my predicament. I need to somehow get the difference between two dates by reversing a function I have to add months and years?
Problem
The date add function provided with PHP >= 5.3 does not add dates in the manner I require.
Example: +3 Months to 30Nov = 2Mar
Solution
I use the function below (code ref 2) to produce the results I need.
Example: +3 Months to 30Nov = 28Feb
However when using the below (code ref 1) to calculate the difference it does so based on the addition function provide with PHP >= 5.3 in that I get 2 instead of 3 months difference between 30Nov and 28Feb.
If anyone could help come up with an accurate date diff based on the code ref 2 logic I, and I'm sure others in the same boat would be very grateful.
<< CODE REF 1 >>
<?php
$datetime1 = new DateTime('2000-11-30');
$datetime2 = new DateTime('2001-02-28');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%m'); // 2
$datetime1 = new DateTime('2000-11-30');
$datetime2 = new DateTime('2001-03-02');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%m'); // 3
?>
<< CODE REF 2 >>
<?php
$datetime = new DateTime('2000-11-30');
$y = 0;
$m = 3;
$d = 0;
if ($d>0){
$datetime->add(new DateInterval('P'.$d.'D'));
}
if ($d<0){
$datetime->sub(new DateInterval('P'.$d.'D'));
}
if ($y!=0){
$init=clone $datetime;
$modifier=$y.' years';
$datetime->modify($modifier);
while ($datetime->format('m')!=$init->format('m')){
$datetime->modify('-1 day');
}
}
if ($m!=0){
$init=clone $datetime;
$modifier=$m.' months';
$back_modifier =-$m.' months';
$datetime->modify($modifier);
$back_to_init= clone $datetime;
$back_to_init->modify($back_modifier);
while ($init->format('m')!=$back_to_init->format('m')){
$datetime->modify('-1 day');
$back_to_init= clone $datetime;
$back_to_init->modify($back_modifier);
}
}
echo $datetime->format('Y-m-d'); // 2001-02-28
?>
SOLUTION FOUND
By changing the way we use the original function we instead find out the number of years and months as desired, many thanks to all the helpful suggestions. The reason for y=1 and m=4 is because the year starts at one and the month starts at one, otherwise it would be 0 and 3 as originally requested if starting at zero.
<?php
function date_yr_mth($date1='2000-11-30',$date2='2001-02-28'){
$y1 = date("Y", strtotime($date1));
$m1 = date("n", strtotime($date1));
$d1 = date("j", strtotime($date1));
$y2 = date("Y", strtotime($date2));
$m2 = date("n", strtotime($date2));
$d2 = date("j", strtotime($date2));
$t2 = date("t", strtotime($date2));
$cm_diff = $m2-$m1;
$cy_diff = $y2-$y1;
if ($d2>=$d1){
$add_mth1 = 1;
}else{
$add_mth1 = 0;
}
$add_mth2 = 12*$cy_diff+$cm_diff;
if ($d2==$t2 && $d2<$d1){
$add_mth3 = 1;
}else{
$add_mth3 = 0;
}
$total_mths = $add_mth1+$add_mth2+$add_mth3;
$arr = array();
$arr['y'] = floor(($total_mths-1)/12)+1;
$arr['m'] = $total_mths-($arr['y']-1)*12;
print_r($arr);
// [y] => 1
// [m] => 4
}
?>
The way to approach this is to extend DateTime and overide the add() and sub() methods to behave as you want them to. That, after all is one of the advantages of OOP.
The way to get your desired behaviours is to set the day of the month to the 1st before doing calling add() or sub() and then restoring the original or highest possible day afterwards.
My first attempt is below, not thoroughly tested, but adding 1 month to 31st Jan gave 28th Feb, which, I believe is your desired behaviour:-
class MyDateTime extends \DateTime
{
public function add($interval)
{
$oldDay = (int)$this->format('d');
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), 1);
parent::add($interval);
$maxDay = (int)$this->format('t');
if($oldDay > $maxDay){
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), $maxDay);
} else {
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), $oldDay);
}
return $this;
}
public function sub($interval)
{
$oldDay = (int)$this->format('d');
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), 1);
parent::sub($interval);
$maxDay = (int)$this->format('t');
if($oldDay > $maxDay){
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), $maxDay);
} else {
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), $oldDay);
}
return $this;
}
public function diff($dateTime2, $absolute = false)
{
if((int)$this->format('t') > (int)$dateTime2->format('t')){
$this->setDate((int)$this->format('Y'), (int)$this->format('m'), (int)$dateTime2->format('t'));
}
if((int)$this->format('t') < (int)$dateTime2->format('t')){
$dateTime2->setDate((int)$dateTime2->format('Y'), (int)$dateTime2->format('m'), (int)$this->format('t'));
}
return parent::diff($dateTime2, $absolute);
}
}
Here is a working example using your exampe dates
Here is an example using the diff() method as you can see it gives a 3 month difference. You can also see that adding the resulting DateInterval to the original date results in the second date.
The sub() method may require a bit more thought, but I don't have time just now. I'll take a more thorough look if I get a few spare minutes later.
This way you would get the absolute difference between months without taking in account the day.
<?php
function getMonthDiff($firstMonth, $secondMonth)
{
$firstMonth = $firstMonth->format("Y") * 12 + $firstMonth->format("m");
$secondMonth = $secondMonth->format("Y") * 12 + $secondMonth->format("m");
return abs($firstMonth - $secondMonth);
}
$datetime1 = new DateTime('2000-11-30');
$datetime2 = new DateTime('2001-02-28');
echo getMonthDiff($datetime1, $datetime2);
echo "<br />";
$datetime1 = new DateTime('2000-11-30');
$datetime2 = new DateTime('2001-03-02');
echo getMonthDiff($datetime1, $datetime2);
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
}