Date problem in PHP - php

I have a piece of PHP that is trying to do this:
1) given a string like "h m s" (where h=hr, m=min, s=sec)
2) Add the time from 1) to time()
3) format the result to look like "y-mth-d-h-min-s"
So say the time is now 01-01-2011 1am, I want it to add "10 0 0", which should give me 01-01-2011 11am, but for some reason at the moment, it does seem to add the string, but it's not accurate.
This is the code I'm using:
$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$values_arr['regx_expdate']);
where $values_arr['regx_expdate'] is the string in the format "h m s", eg. "10 0 0".
The main question is how would time() know if "10 0 0" is actually 10hrs 0min 0min, and not 10days 0hr 0min??

It does not.
It will cast it to int, interpret it as seconds and add it to the result of time().
Some code that could do as you describe would be:
list ($h,$m,$s) = explode(' ', $values_arr['regx_expdate'], 3);
$difference = 60*60*$h + 60*$m + $s;
$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$difference);

Easiest method I can think of is to extract each token from $values_arr['regx_expdate'], add up the seconds and simple add it to time().
For example
if (preg_match('/^(\d{1,2}) (\d{1,2}) (\d{1,2})$/', $values_arr['regx_expdate'], $units)) {
$seconds = $units[3] + ($units[2] * 60) + ($units[1] * 3600);
$newTimestamp = time() + $seconds;
}

After parsing your input string into Hours Minutes and Seconds, it might be worth reorganizing said array of values into a string that PHP's strtotime can process.

This little function may help, you may customize it to suit your purpose:
function AddingDaysFromNow($number_of_days)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
// today is now time return in seconds
$addingTime = $today + (86400 * $number_of_days);
// adding to advance it
//choice a date form at here
return date("Y-m-d", $addingTime);
}
//use it as
$expireDate = AddingDaysFromNow(2); // assume the 2 is advance to 2 days ahead
// return the day in future
Good luck!

To handle and convert dates in php you should first force everything into unixtimestamp and then you give it the structure you want
$date = date("THE-DATE-FORMAT-YOU-WANT", "THE-DATE-YOU-WOULD-LIKE-TO-CONVERT-IN-SECONDS");
//For example.
$new_date = date("Y-m-d H:i:s", strtotime($old_date));
$now = date("Y-m-d H:i:s", time());

Related

how to divide hours in php?

I have tried to search for the answer for my problem for quite a while now and I did not solve it yet. I am new to PHP.
Problem.
Divide 2:00 by 2 (hr/2) = 1:00 //format h:i
Thanks.
I think the safest way is to convert to seconds and use date to display it.
$time ="3:00";
list($hours, $minutes) = explode(":", $time);
$minutes += $hours*60;
$seconds = $minutes*60;
date_default_timezone_set ("UTC"); // makes sure there is no DST or timezone added to result
echo "new time: " . date("h:i", $seconds/2); // 01:30
Your question states "h:i" format yet it's written as "1:00".
To get 1:00 you need to use format "G:i".
https://3v4l.org/4MjVQ
For the record, dividing time is trivial in any programming/scripting language. Because if we are talking about a timestamp, dividing that would make no sense, because a timestamp is a particular point on the line of chronology.
Time duration in the other hand, could be divided. However, I am not so sure if php's API has any implementation for time duration handling. Still you can go on for your own customized implementation to handle time intervals. It would be something like follows.
<?php
#We need at least two timestamps to get a duration
$time1 = new DateTime("2018-4-23 10:00:00");
$time2 = new DateTime("2018-4-23 11:00:00");
$durationInSeconds = ($time2->getTimestamp()) - ($time1->getTimestamp()); //Get the interval in seconds
#echo $durationInSeconds; // Gives you 3600 seconds
# Now you can divide these seconds into anything you prefer.
# Let's say I want two intervals. This means, I have to go for the timestamp in between the two. I could do that by simply adding half the amount of seconds
$halfDurationInSeconds = $durationInSeconds / 2;
$time1->add(new DateInterval("PT".$halfDurationInSeconds."S")); // adds 1800 secs
echo $time1->format('Y-m-d H:i:s');
Its very simple. Use strtotime
$your_time = "12:00";
date_default_timezone_set ("UTC");
$secs = strtotime($your_time ) - strtotime("00:00:00");
echo date("H:i:s",$secs / 2);
I think we can also use multiplication here. Thanks for the suggestions above. It really did help me a lot. This is my modified code for the suggestions above.
function multiplyTime ($multiple, $prescribeWorkingHrs) {
list($hours, $minutes) = explode(":", $prescribeWorkingHrs);
$minutes += $hours*60;
$seconds = $minutes*60;
$product = $seconds * $multiple;
return date("h:i", $product);
}
Results:
multiplyTime(0.75, "8:00") = "6:00"
multiplyTime(0.5, "8:00") = "4:00"
multiplyTime(0.25, "8:00") = "2:00"
Hope this will help too. Thanks

Multiple hour by a number

I have something like that for example: 01:06:22 this represents 1hour, 6minutes and 22seconds. I want to take that, and multiple it by 6 and add it to some other hour such as 04:23 which is 4AM and 23Minutes not 4hours and 23 minutes.
Basically, as a result I expect that:
01:06:22
* 6 = 6hours 38minutes canceling the remaining seconds which are 12 in this case
Now, I want to take that and append it to other hour, 04:23 in this case, so the result would be:
11:01.
I have no clue how to start and do it, unfortunately.
Any help is appriciated!
Clarifications
The time that I have to multiple by 6 will never exceed 2 hours.
All the times are in the same format.
With DateTime it is simple:
$time = '01:06:22';
$dateSeconds = new DateTime("1970-01-01 $time UTC");
$seconds = $dateSeconds->getTimestamp() * 6;
$interval = new DateInterval('PT'.$seconds.'S');
$date = new DateTime('1970-01-01 04:23:00 UTC');
$date->add($interval);
echo $date->format('H:i:s');
Other solution with strtotime and gmdate. (Similar to Suresh but working):
$date = strtotime('1970-01-01 01:06:22 UTC');
$add = strtotime('1970-01-01 04:23:00 UTC');
$date = (($date*6)+$add);
echo gmdate('H:i:s', $date);
This is a solution if you want to implement it yourself.
The thing about timecode is that it can become really heavy with the if the if conditions etc if you don't do it right.
The best Way I thought of to deal with this is to convert everything to second.
so 01:06:22 would become:
numberOfSecond = 22 + 06 * 60 + 01 * 60 * 60
How to get the 22, 06 etc from the String? You can use Regex.
What you will need:
a function to extract the different values (hours, minute, second)
a function to convert the timecode into second
a function to convert back into timecode
the functions to multiply, add etc...
You might want to create a class for it.
You can try like this:
$date = strtotime('01:06:22');
$add = strtotime('00:04:23');
$date = ($date*6)+$add;
echo date('H:i:s', $date);
Note: Code is not tested.
First of all you want to multiply a time span by a factor. The easiest way to do this is to convert the span to seconds and do a straight multiply:
$date =DateTime::createFromFormat('!H:i:s', '01:06:22', new DateTimeZone('UTC'));
$seconds = $date->getTimestamp();
This code works by pretending that the time is a moment during the Unix epoch start so that it can then get the number of seconds elapsed since the epoch (the timestamp). That number is equal to the duration of the time span in seconds. However, it is vitally important that the input is interpreted as UTC time and not as something in your local time zone.
An equivalent way of doing things (as long as the input is in the correct format) which is lower-tech but perhaps less prone to bugs would be
list($h, $m, $s) = explode(':', '01:06:22');
$seconds = $h * 3600 + $m * 60 + $s;
Now the multiplication:
$seconds = $seconds * 6;
If you want to only keep whole minutes from the time you can do so at this stage:
$seconds = $seconds - $seconds % 60;
The final step of adding the result to a given "time" is not clearly specified yet -- does the reference time contain date information? What happens if adding to it goes over 24 hours?
Self explanatory :
$initialTime = '01:06:22';
$timeToAdd = '04:23';
$initialTimeExploded = explode( ':' ,$initialTime );
$initialTimeInMintues = ( $initialTimeExploded[0] * 60 ) + $initialTimeExploded[1];
$initialTimeInMintuesMultipliedBySix = $initialTimeInMintues * 6;
$timeToAddExploded = explode( ':' ,$timeToAdd );
$timeToAddExplodedInMintues = ( $timeToAddExploded[0] * 60 ) + $timeToAddExploded[1];
$newTimeInMinutes = $initialTimeInMintuesMultipliedBySix + $timeToAddExplodedInMintues;
$newTime = floor( $newTimeInMinutes / 60 ) .':' .($newTimeInMinutes % 60);
echo $newTime;
Result :
10:59

Why do I get unexpected hour when substracting two times

I have this simple function to subtract time: the input values are:
$current = '23:48:32';
$arrival = '23:41:48';
$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
$waitingTime = $time; // 21:06:44
Looks like the diff for the minutes is correct, I am not sure why I am getting the 21 in front of the minutes. It should be 00:06:44.
Any help is appreciated.
Thank you.
try using gmdate()
$time = gmdate( "H:i:s", strtotime($current) - strtotime($arrival));
You can't expect this code to give you an interval.
the strtotime($current) - strtotime($arrival) line calculates a interval in seconds but when you pass it to date it assumes your speaking of an interval since epoch. so you get timezone translated value for $time; you must have gotten 9 because your probably behind UTC
use strtotime($current) - strtotime($arrival) / 3600 for hours and remainder divide by 60 for minutes. and then seconds
That's why PHP has DateTime & DateIntervals:
<?php
header('Content-Type: text/plain; charset=utf-8');
$current = '23:48:32';
$arrival = '23:41:48';
$current = DateTime::createFromFormat('H:i:s', $current);
$arrival = DateTime::createFromFormat('H:i:s', $arrival);
$diff = $current->diff($arrival);
unset($current, $arrival);
echo $diff->format('%H:%I:%S');
?>
Output:
00:06:44
This code echo 00:06:44!
$current='23:48:32';
$arrival='23:41:48';
$time = date( "H:i:s", strtotime($current) - strtotime($arrival));
echo $time;//00:06:44
What exactly is your problem?

Transform DateTime variable into minutes

There is the following variable:
$datetime = '2012-09-09 01:40';
I need to extract hours and minutes, and then to transform them into minutes. In this example, I would need to get 100 (1 hr 40 min = 60 min + 40 min). How can I quickly do this using PHP functions?
The strtotime() and date() functions are not recommended anymore. Use the DateTime class.
$datetime = '2012-09-09 01:40';
$d = new DateTime($datetime);
var_dump( $d->format('G') * 60 + $d->format('i') );
$string = '2012-09-09 01:40';
$epoch = strtotime($string);
echo date('i', $epoch) + (60 * date('H', $epoch));
Outputs 100
Basically what happens here is the string date gets converted to Unix/Epoch time. Then, using date() it adds the number of minutes (i) to 60 times the number of hours (h).
$datetime = strtotime('2012-09-09 01:40');
$hour = date('H',$datetime);
$min = date('i',$datetime);
echo ($hour*60 + $min);
You can use preg_split like this:
$parts=preg_split("/(\d\d):(\d\d)/",$datetime,-1,PREG_SPLIT_DELIM_CAPTURE);
$mins=($parts[1]*60)+$parts[2];
Now $mins=100 when $datetime is like in your post

Github API, decode "date"

Im using Github's api to get my latest commits, and the date format returned looks like this
2012-01-25T11:23:28-08:00
I tried to do it like this:
$date = explode('T', $next['commit']['author']['date']);
$time = strtotime($date[0] .' '. $date[1]);
$date = date('M j, Y g:i a', $time);
But it didnt turn out right as php thought I was subtracting 8 hours from the time (because of the timezone). I would like to keep the timezone but i have no clue how to parse that. Does anyone know how to have it where the time is correct and shows the time zone abbreviation (GMT, PST etc etc )?
It cannot get any simpler than this:
$a = new DateTime("2012-01-25T11:23:28-08:00");
echo $a->format("Y-m-d H:i:s");
//outputs 2012-01-25 11:23:28
See the documentation of the DateTime class for more info.
The simple, mechanical, solution is to break the date down yourself completely:
$date = substr($next['commit']['author']['date'], 0, 10);
$time = substr($next['commit']['author']['date'], 11, 9);
$zone = substr($next['commit']['author']['date'], 20, 6);
list($y, $m, $d) = explode('-', $date);
list($h, $i, $s) = explode(':', $time);
$zh = substr($zone, 1, 2);
$zm = substr($zone, 4, 2);
if (substr($zone, 0, 1) == '-'){
$h -= $zh;
$m -= $zm;
}else{
$h += $zh;
$m += $zm;
}
$ts = gmmktime($h,$i,$s,$m,$d,$y);
This will give you a timestamp in UTC.
The issue is with "shows the time zone abbreviation" - you can't find a abbreviation for a given offset, because there can be several - you can't tell which of the e.g. +01:00 timezones the date is in - could be european, african, or bristish summer time.
It really depends what you want to do with the data.

Categories