In php is there a way to turn two integers (09 and 30) into into type time (9:30). I need this function so I can INSERT these number into a column in MySQL of type time.
setTime
$datetime = new DateTime();
$datetime->setTime(9, 30, 0);
DateTime::format ( string $format )
will do
$str = '09:' +'30';
$date = DateTime($str);
$date->format('H:i')
In php is there a way to turn two integers (09 and 30) into into type time (9:30). I need this function so I can INSERT these number into a column in MySQL of type time.
Yes, by formating them as string:
$hr = 9;
$min = 30;
$time = sprintf('%02d:%02d', $hr, $min);
echo $time; # 09:30
As hakre said, use sprintf.
$hours = 9;
$minutes = 30;
$time = sprintf("%02d:%02d:00", $hours, $minutes);
$a1 = array("09","30");
$date implode(":",$a1);
Related
I need to show the difference between two times in PHP I use strtotime() function to convert my times to integer but my problem is the result not matched what I expected
<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00
But the difference is 3:00:00 how to calculate this?
You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.
<?php
$hour1 = '12:00:00';
$hour2 = '09:00:00';
$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);
$diff = $o1->diff($o2,true); // to make the difference to be always positive.
echo $diff->format('%H:%I:%S');
Demo: https://3v4l.org/X41pv
You can do that:
$hour1 = '12:00:00';
$hour2 = date('h', strtotime('9:00:00'));
$avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
echo $avg; //3:00:00
i have two different break time
default break time
extra break time
here i want to sum of two times and display 12 hrs format
EX :
$default_time = "00:30";
$extra_time = "00:25";
my expected output : 00:55
but now display 01:00
this is my code
$default_time = $work_data->break_time;
$break_time = $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
Here is the function you can calculate total time by passing the arguments to functions.
$hours, $min are supposed variable which is zero
$default_time = "00:30";
$break_time = "00:25";
function calculate_total_time() {
$i = 0;
foreach(func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if( $h = floor($i / 60) ) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo calculate_total_time($default_time, $break_time); # 00:55
There is one function call to strtotime function too much.
You should leave out the strtotime() call in the last line, as $total_break already is a UNIX timestamp:
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",$total_break);
The problem is that you're trying to add too specific timestamps, but what you're trying to achieve is adding two durations. So you need to convert those timestamps into durations. For that you need a base, which in your case is 00:00.
$base = strtotime("00:00");
$default_time = $work_data->break_time;
$default_timestamp = strtotime($default_time);
$default_duration = $default_timestamp - $base; // Duration in seconds
$break_time = $work_data->extra_time;
$break_timestamp = strtotime($break_time);
$break_duration = $break_timestamp - $base; // Duration in seconds
$total_break = $default_duration + $break_duration; // 55 min in seconds
// If you want to calculate the timestamp 00:55, just add the base back to it
echo date("H:i", $base + $total_break);
Consider using standard DateTime and DateInterval classes. All you will need is to convert your second variable value to interval_spec format (see http://php.net/manual/en/dateinterval.construct.php for details):
$defaultTime = "00:30";
$breakTime = "PT00H25M"; // Or just 'PT25M'
$totalBreak = (new DateTime($defaultTime))->add($breakTime);
echo $totalBreak->format('H:i');
You could try the following code fragment:
$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);
<?php
$time = "00:30";
$time2 = "00:25";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
print_r($result);
?>
Use below code you will definitely get your answers.
$default_time = "00:30:00";
$extra_time = "00:25:00";
$secs = strtotime($extra_time)-strtotime("00:00:00");
$result = date("H:i:s A",strtotime($default_time)+$secs);
echo $result;die;
You can modify above code as per your need.
You could try the following:
$default_time = $work_data->break_time;
$date_start = new DateTime($default_time);
$break_time = $work_data->extra_time;
$interval = new DateInterval("PT" . str_replace(":", "H", $break_time) . "M");
$date_end = $date_start->add($interval);
echo $date_end->format("H:i");
Note that this doesn't account for times which span a 24 hour period
I wish to multiply 2 variables so that one of them is in the hour format (hh:mm),
How can I do so? The answer I am getting is 0:
<?php
$num = 5;
$timeUnit = "00:01";
$waitingTime = $num * $timeUnit;
echo $waitingTime;
I need to get 00:05 (5 min) in the output, but I am getting 0.
Hope this will help you
$num=100;
$timeUnit="00:02";
$timeUnit;
$time=explode(":",$timeUnit);
$waitingTime=$num*$time[1];
$minute = sprintf("%02d", ($waitingTime%60));
$hour = sprintf("%02d", ($waitingTime/60));
$current_time = floor($hour).':'.($minute);
echo $current_time;
$num=20;
$timeUnit="00:03";
$time=explode(":",$timeUnit);
$waitingTime=$num*$time[1];
$sec=$time[0]+$waitingTime%60;
$hour=floor($waitingTime/60);
$timeUnit1="".$hour.":".$sec."";
$current=strtotime($timeUnit1); //seconds of current time
echo date("H:i",$current);
You can do like this
I ended up converting the time into seconds, did the multiply and converted it to "time format" again:
$num=200;
$timeUnit="00:01:00";
$time=explode(":",$timeUnit);
$sec=$time[1]*60;
$sec=$sec*$num;
$diff = $sec;
$format = sprintf('%02d:%02d:%02d', ($diff / 3600), ($diff / 60 % 60), $diff % 60);
echo $format;
Thanks for your help
You can't compute string and digits this way.
All you would have to do would be to create a function/method that would implement the behavior you want and use it
How can I use the following 16-digit timestamp (from an XML file) with PHP's date() function?
1295076698126000 // 15-01-2011 08:31:38.126
1286697695521000 // 10-10-2010 10:01:35.521
Those timestamps are in microseconds. However, since PHP uses integers for timestamps in seconds with date(), you won't be able to obtain the microsecond value. You're still able to print the rest of the date by dividing the timestamp by a million (1 million microseconds = 1 second), and passing the quotient to date():
// "u" will always be printed as 000000 regardless of actual microseconds
echo date('d-m-Y H:i:s.u', 1295076698126000 / 1000000);
EDIT: Hacky, but you can perform manual arithmetic to get the milliseconds and output it separately as a workaround, like this:
$xml_timestamp = 1295076698126000;
$seconds = $xml_timestamp / 1000000;
$microseconds = $seconds - floor($seconds);
$seconds = floor($seconds);
// 1 millisecond = 1000 microseconds
// Milliseconds, because your desired output is 3 decimal places long, not 6
$milliseconds = round($microseconds * 1000);
$format = 'd-m-Y H:i:s.' . sprintf('%03d', $milliseconds);
echo date($format, $seconds);
For reusability the DateTime class is a good option. Or, a custom function:
function date_milliseconds($format, $timestamp = NULL) {
$seconds = ($timestamp === NULL) ? microtime(true) : $timestamp / 1000000;
$microseconds = $seconds - floor($seconds);
$seconds = floor($seconds);
$milliseconds = round($microseconds * 1000);
$format = preg_replace('/(?<!\\\\)u/', sprintf('%03d', $milliseconds), $format);
return date($format, $seconds);
}
echo date_milliseconds('d-m-T H:i:s.u', floatval($xml_timestamp));
I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.
I want to check whether the current time is between these two values. I am checking this with the code
$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
$stat = "open";
} else {
$stat = "close";
}
But I am always getting the $stat as Close. What may cause that?
you can try using strtotime
$st_time = strtotime($resttimefrom);
$end_time = strtotime($resttimeto);
$cur_time = strtotime(now);
then check
if($st_time < $cur_time && $end_time > $cur_time)
{
echo "WE ARE CLOSE NOW !!";
}
else{
echo "WE ARE OPEN NOW !!";
}
i hope this may help you..
A simple yet smart way to do this is to remove the ':' from your dates.
$resttimefrom = 73000;
$resttimeto = 223000;
$currentTime = (int) date('Gis');
if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
$stat="open";
}
else
{
$stat="close";
}
$today = date("m-d-y ");
$now = date("m-d-y G:i:s");
if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
$stat = 'open';
else
$stat = 'close
Try reformatting them into something that you can compare like that. For example, numbers:
$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);
$time = mktime(date('H'),date('i'),date('s'));
You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().
Just convert your dates to a Unix Timestamp, compare them, you have your results! It might look something like this:
$time =date("G:i:s");
$time1 = strtotime($time);
$resttimefrom1 = strtotime($resttimefrom );
$resttimeto1 = strtotime($resttimeto );
if ($time1 >$resttimefrom and $time1 <$resttimeto)
{
$stat="open";
}
else
{
$stat="close";
}
The date function returns a string, so the comparison you're making would be a string comparison - so 7:30 would be more than 22:30
It would be much better to use mktime, which will return a Unix timestamp value (integer) so it would make for a better comparison
$currentTime = mktime();
$resttimefrom = mktime(hour,min,second);
http://php.net/mktime
The trick to manipulating and comparing dates and times in PHP is to store date/time values in an integer variable and to use the mktime(), date() and strtotime() functions. The integer repesentation of a date/time is the number of seconds since midnight, 1970-Jan-1, which is referred to as the 'epoch'. Once your date/time is in integer form you'll be able to efficiently compare it to other dates that are also in integer form.
Of course since you'll most likely be receiving date/time values from page requests and database select queries you'll need to convert your date/time string into an integer before you can do any comparison or arithmetic.
Assuming you are sure that the $resttimefrom and $resttimeto variables contain properly formatted time you can use the strtotime() function to convert your string time into an integer. strtotime() takes a string that is formatted as a date and converts it to the number of seconds since epoch.
$time_from = strtotime($resttimefrom);
$time_to = strtotime($resttimeto);
Side note: strtotime() always returns a full date in integer form. If your string doesn't have a date, only a time, strtotime() return today's date along with the time you gave in the string. This is not important to you, though, because the two dates returned by strtotime() will have the same date and comparing the two variables will have the desired effect of comparing the two times as the dates cancel each other out.
When you compare the two integers keep in mind that the earlier the date/time is, the smaller its integer value will be. So if you want to see if $time_from is earlier than $time_to, you would have this:
if ($time_from < $time_to)
{
// $time_from is ealier than $time_to
}
Now to compare a date/time with the current system date/time, just use mktime() with no parameters to represent the current date/time:
if ($time_from < mktime())
{
// $time_from is in the past
}
$firstTime = '1:07';
$secondTime = '3:01';
list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);
$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
$Time1 = date_parse($time);
$seconds1 = $Time1['hour'] * 3600 + $Time1['minute'] * 60 + $Time1['second'];
$Time2 = date_parse($current_time);
$seconds2 = Time2['hour'] * 3600 + Time2['minute'] * 60 + Time2['second'];
$actula_time = $seconds1 - $seconds2;
echo floor($actula_time / 3600) .":". floor(($actula_time / 60)%60) .":". $actula_time%60;
As Col. Shrapnel Said i am doing by converting all the time in to seconds and then compare it with current time's total seconds