converting array values to time in php - 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

Related

PHP date timezone producing unexpected result off by an hour

This timezone problem is driving me crazy and hoping someone can put me in my place fast as it's likely super simple
$timezone = 'EST';
$datetimenow = new DateTime("Now", new DateTimeZone($timezone));
$today = $datetimenow->format("m/d/Y"); // = 03/26/2021
// FOR LOOP
$filter = $today .' '.$details->data->time['start']; // where start = 8:30 PM
// END FOR LOOP
$datetimeevent = new DateTime($filter, new DateTimeZone($timezone));
// datetimeevent print_r = correct =
DateTime Object
(
[date] => 2021-03-26 20:30:00.000000
[timezone_type] => 2
[timezone] => EST
)
$filter = $datetimeevent->getTimestamp();
// $filter = 1616808600
// 1616808600 =
//String:
//GMT: Saturday, March 27, 2021 1:30:00 AM
//Your time zone: Friday, March 26, 2021 9:30:00 PM GMT-04:00 DST
huh? how is 8:30 becoming 9:30 on what should be a straight up conversion?

Days calculation is not given correct days

I would like to calculate days based on two dates but it's given incorrect count of days.
I have 2 variables
$date=$date[1]; Is coming from Database
$now =date('d/m/Y'); Current date
$date variable value is(comes from db) 05/03/2019
I used following script for count days based on two dates but its return 120 days.
Method 1
$date=$date[1]; `Is coming from Database`
$now =date('d/m/Y');
$date1 = new DateTime($now);
$date2 = new DateTime($date);
$diff = $date2->diff($date1)->format("%a");
Method 2
$datetime1 = new DateTime($now);
$datetime2 = new DateTime($date);
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
But it's returns wrong days in following output
Difference: 0 years, 4 months, 120 daysDateInterval Object
(
[y] = 0
[m] = 4
[d] = 0
[h] = 0
[i] = 0
[s] = 0
[invert] = 0
[days] = 120
)
Why this given wrong output of days ?
If you use 'd/m/Y' format you should use createFromFormat function to convert string date to date object. For example:
$date1 = new \DateTime();
$date2 = \DateTime::createFromFormat('d/m/Y', '05/03/2019');
$diff = $date2->diff($date1)->format("%a");

Add Date and time in PHP

Hi I have a date string taken from database. And it's like
$date = '2016-03-21 11:00:00';
And I have a time string taken from database.
$time = '02:30:00'
Is there a way to add these two and get like these in PHP?
$newtime = '2016-03-21 13:30:00';
Use preg_replace to transform your $time value:
$date = '2016-03-21 11:00:00';
$time = '02:30:00';
$str = "$date + ".preg_replace( '/:(\d+):(\d+)$/',' hours, \1 minutes, \2 seconds',$time );
$date = new DateTime( $str );
echo $date->format('Y-m-d H:i:s');
Will print:
2016-03-21 13:30:00
With preg_replace we transform 02:30:00 in 02 hours, 30 minutes, 00 seconds and, postponing it to $date, we obtain this string:
2016-03-21 11:00:00 + 02 hours, 30 minutes, 00 seconds
directly accepted by DateTime class.
Read more about DateTime
I'm sure there's a better way to do this but:
$date = new DateTime($time);
$int = new DateInterval($date->format("\P\TH\Hi\Ms\S"));
$dateTime = new DateTime($date);
return $dateTime->add($int);

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);

date_time_set issue with 2 different dates

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;

Categories