date_time_set issue with 2 different dates - php

I'm trying to set the time between 2 variables but when I check it copies the change on the 2 time. For example, I select 1:00 and 23:00 , both dates show 23:00 only. I can't seem to get why it's showing like that even if I have already different variables for each time. I need to show the different dates.
Input Dates:
01:30 and 21:00
My code:
$date = $_POST['datepicker'];
$time1 = $_POST['timepicker'];
$time2 = $_POST['timepicker2'];
$time1_array = explode(":",$time1);
$time2_array = explode(":",$time2);
$date = $_POST['datepicker'];
$date = new DateTime($date);
$date2 = $date;
$datefinal1 = date_time_set($date, $time1_array[0], $time1_array[1], 00);
$datefinal2 = date_time_set($date2, $time2_array[0], $time2_array[1], 59);
$result = $datefinal1->format('Y-m-d H:i:s');
$result2 = $datefinal2->format('Y-m-d H:i:s');
print_r($datefinal1);
Sample output that I am getting:
DateTime Object ( [date] => 2015-03-17 21:00:59 [timezone_type] => 3
[timezone] => Europe/Berlin )
even if I should be getting the $datefinal2's value.

Objects are copied by reference, not value. If you assign one object to a new variable both point to the same object so changing one changes the other. To copy an object you need to use clone.
$date2 = $date;
should be:
$date2 = clone $date;

Related

PHP add 24 hours to a specific date

I need to add 24 hours to a date that will be stored in a variable.
Example:
$date = "2019-11-20 05:05:00"; => $date = "2019-11-21 05:05:00"; (24 hours have been added).
I've tried some options, but I haven't been successful in any of them.
I have tried with strtotime() method:
$new_time = date("Y-m-d H:i:s", strtotime('+24 hours')).
If the sintaxe is like above, then it works, but it doesn't seem to accept a pre-defined date or a variable, like this:
$date = "2019-11-20 05:05:00";
$new_time = date($date, strtotime('+24 hours'));
Or this:
$new_time = date("2019-11-20 05:05:00", strtotime('+24 hours'));
In both cases the output is the same as the input date, without the +24 being added.
I've experimented the modify() method.
$date = "2019-11-20 05:05:00";
$dateTime= new DateTime($date);
$dateTime->modify('+24 hours');
print_r($dateTime);
echo $datetime->date;
Output (if I print the objetct):
DateTime Object
(
[date] => 2019-11-21 05:05:00.000000
[timezone_type] => 3
[timezone] => Europe/Paris
)
2019-11-21 05:05:00.000000
Output (if I don't print the objetct):
Notice: Undefined property: DateTime::$date
It sort of works, but the problem is that I can access the date property only if I print the whole dateTime object, what would trouble my application. Besides that, apparently, these properties don't really exist, they seem to be more like a bug, since they are not described in the documentation as properties of the dateTime object.
I am trying to use getTimestamp(), but I couldn't add time to it.
How could I do that?
The PHP manual has a complete example;
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P1D'));
echo $date->format('Y-m-d') . "\n";
The value for DateInterval could be changed In 'PT24H'. During daylight savings changes 24 hours is not the same as 1 day, which PHP will arrange for you with the proper timezone configuration.
If you're working with DateTime object, all you have to do is create an interval and then use add method. Like so:
$dateTime = new DateTime();
$interval = new DateInterval("P0Y0M0DT24H0M0S");
$dateTime->add($interval);

converting array values to time in php

I have an array which contains time values in GMT. :
Array
(
[0] => Array
(
[h] => 5
[m] => 0
)
)
Here Array[0][0] is the array for start time and Array[0][1] is the array for end time.
Now what I am creating time using date time as:
$timezone = new DateTimeZone("Asia/Kolkata"); //Converting GMT to IST.
$startTime = new DateTime();
$startTime->setTime($Array[1][0]["hour"], $Array[1][0]["minute"]);
$startTime->setTimezone($timezone);
$startTime->format('h:i a'); //output 10:30 PM // Should be 10:30 AM
$endTime = new DateTime();
$endTime->setTime($Array[1][1]["hour"], $Array[1][1]["minute"]);
$endTime->setTimezone($timezone);
$endTime->format('h:i a'); //output 10:30 PM //ok
So My $startTime and $endTime both has the same value of `10:30` PM but I want the startTime to have value of `10:00 AM`because its period was `AM` in the array.
When creating new Datetime object You have to specify timezone, because default value is taken from PHP configuration and this may not be set to GMT. So initialization of $startTime and $endTime should be:
$startTime = new DateTime('', new DateTimeZone('GMT'));
$endTime = new DateTime('', new DateTimeZone('GMT'));
Then when You are using setTime() You have to add 12 hours when PM period is taken. It should look like that:
$startTime->setTime($Array[1][0]["hour"] + ($Array[1][0]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
$endTime->setTime($Array[1][1]["hour"] + ($Array[1][1]["period"] === 'PM' ? 12 : 0), $Array[1][0]["minute"]);
Rest of the code looks fine, besides in You example $Array[1] is undefined. $Array[0] is set.
You could also use DateTime::createFromFormat():
$d = DateTime::createFromFormat('g:m A', '5:30 PM', new DateTimeZone('GMT'));
$d->setTimeZone(new DateTimeZone('Asia/Kolkata'));
var_dump($d->format('Y-m-d H:i:s'));
Gives:
string(19) "2017-03-16 22:30:00"
You can create the string '5:30 PM' by combining the elements of your array. Please note that you must add a leading 0 to the minutes if they are less than 10, e.g: 9 minutes -> 09

Get next to next monday in PHP

How can i get 2nd monday after the input date?
i have solution but that not feasible
$date = new DateTime();
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');
$date = new DateTime($next_monday);
$date->modify('next monday');
$next_monday = $date->format('Y-m-d');
Please suggest me some method to do so.
Your DateTime object's modify method takes the same type of arguments that strtotime does. You're already using 'next monday', you just need to use 'second monday' instead.
$date->modify('second monday');
echo $date->format('Y-m-d');
Also, in case you didn't know this, some of the DateTime methods can be chained:
echo $date->modify('second monday')->format('Y-m-d');
You can do it with strtotime() but if you think it is too costly, you can use date and DateInterval as well.
$date = new DateTime('2017-02-15 13:03:00');
// move back to past Monday
$num = (date("w", $date->getTimestamp())) - 1;
$offset = new DateInterval("P{$num}D");
$offset->invert = 1;
// move forward two weeks
$interval = new DateInterval('P2W');
$next_second_monday = $date->add($offset)->add($interval);
And $next_second_monday will be:
DateTime Object
(
[date] => 2017-02-27 13:03:00.000000
[timezone_type] => 3
[timezone] => UTC
)
There is probably another way to do so but using MomentPHP You could get the start of today's week, adding 1 day ( to get to monday ) and then adding two week, you would get to the second next monday.Something like that :
<?php
$m = \Moment\moment();
$sunday = $m->startOf('week');
$monday = $sunday->addDays(1);
$2nextMonday = $monday->addWeeks(2);

Add given time to tomorrows date in PHP

This might be fairly easy but can't seem to figure it out.
This is what I want to get;
$t = 12:00
$todaysdate = 2015-11-30
I want to get $tomorrowsdate with $t appended to it
$tomorrowsdate = 2015-12-01 12:00
So basically I want to be able to add a given time to next day.
It's important to define them as a string if you wanna use strtotime. Otherwise, you will get freaky results e.g. the year 1970 ;)
$t = '12:00';
$todaysdate = '2015-11-30';
$tomorrowsdate = date('Y-m-d', strtotime("{$todaysdate} + 1 day")) . " {$t}";
echo $tomorrowsdate;
Incase you want to use object oriented style use the following;
$today = new DateTime(); //today (2015-12-29)
$tommorow = $today->add(new DateInterval('P1D')); // add one day
echo $tommorow->format('Y-m-d H:i'); // echo results in desired format eg. 2015-12-30 12:36
// incase that 12:00 is important..
$tommorow->setTime(12,0);
echo $tommorow->format('Y-m-d H:i'); // 2015-12-30 12:00

How to check if the dates are not the same

I try to write a script that can calculate the difference between two dates, in days, and the diff does not behave as I need to.
More specific, lets say we have the following two date/times:
2015-03-18 23:00
2015-03-19 02:00
The actual time difference is four hours, and in this terms the diff works fine !
But what I like to know is, if the calendar date has been change, and what is the actual difference.
So in the example above, the calendar dates having 1 day difference.
In the following example
2015-03-18 23:00
2015-03-21 02:00
I have three days difference. So how can I calculate this date difference ?
At the moment I use the following code:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
$interval = $datetime1->diff($datetime2);
echo "<pre>";
print_r($interval);
echo "</pre>";
and the result is the following:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 3
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
Is there any idea ? Thanks ...
A really simple solution
Notice: this will only work if the days are in the same month.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$difference = $datetime2->format('d') - $datetime1->format('d'); //3
Clean solution
You could remove everything from the date, but the year, month and day and use diff() as you already did.
$datetime1 = new DateTime('2015-03-18 23:00');
$datetime2 = new DateTime('2015-03-21 02:00');
$datetime1modified = new DateTime($datetime1->format('Y-m-d'));
$datetime2modified = new DateTime($datetime2->format('Y-m-d'));
$difference = $datetime1modified->diff($datetime2modified)->d; //3
you surely could use a function like this:
$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");
$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and
// so on to get the h:m:s out of it
or if you more into the build in php functions then something like this might suit your needs:
$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');
$interval = date_diff($date_a,$date_b);
echo $interval->format('%h:%i:%s');
best regards.
What you can do is remove the Time from each of the dates and then calculate.
example:
$datetime1 ='2009-10-11 23:30';
$datetime2 = '2009-10-12 02:30';
$date1_explode = explode($datetime1,' ');
$date1_explode = explode($datetime1,' ');
$date = $date1_explode[1];
$date = $date2_explode[1];
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime1);
$interval = $date1->diff($date2);
echo "<pre>";
print_r($interval);
echo "</pre>";
If you don't care about the hours and want to know only if the date changed you can try to diff the dates after you set them to the same hour:
$datetime1 = new DateTime('2009-10-11 23:30');
$datetime2 = new DateTime('2009-10-12 02:30');
// Work on duplicates to not change the original objects if they are needed later
$date1 = clone $datetime1;
$date2 = clone $datetime2;
// Set the same hour on both $date1 and $date2
$date1->setTime(0, 0, 0);
$date2->setTime(0, 0, 0);
// Now you can simply compare $date1 to $date2 to see if they are equal
if ($date1 == $date2) {
echo('$datetime1 and $datetime2 are on the same date.');
} else {
echo('$datetime1 and $datetime2 are on different dates.');
}
// Or you can compute the difference
$diff = $date2->diff($date1);
// and format it as you like
echo('There are '.$diff->format('%d').' days between '.$date1.' and '.$date2);

Categories