Getting Hour and Minute in PHP - php

I need to get the current time, in Hour:Min format can any one help me in this.

print date('H:i');
$var = date('H:i');
Should do it, for the current time. Use a lower case h for 12 hour clock instead of 24 hour.
More date time formats listed here.

Try this:
$hourMin = date('H:i');
This will be 24-hour time with an hour that is always two digits. For all options, see the PHP docs for date().

print date('H:i');
You have to set the correct timezone in php.ini .
Look for these lines:
[Date]
; Defines the default timezone used by the date functions
;date.timezone =
It will be something like :
date.timezone ="Europe/Lisbon"
Don't forget to restart your webserver.

Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use
date_default_timezone_set() then use one of the supported timezones.

function get_time($time) {
$duration = $time / 1000;
$hours = floor($duration / 3600);
$minutes = floor(($duration / 60) % 60);
$seconds = $duration % 60;
if ($hours != 0)
echo "$hours:$minutes:$seconds";
else
echo "$minutes:$seconds";
}
get_time('1119241');

In addressing your comment that you need your current time, and not the system time, you will have to make an adjustment yourself,
there are 3600 seconds in an hour (the unit timestamps use), so use that. for example, if your system time was one hour behind:
$time = date('H:i',time() + 3600);

You can use the following solution to solve your problem:
echo date('H:i');

<?php
date_default_timezone_set('Asia/Qatar');
$DateAndTime = date('m-d-Y h:i:s a', time());
echo "<h3>The current date and time are <h3 style='color:B-G'> $DateAndTime.</h3></h3>";
?>

Related

Get difference between 2 date_time in minutes

Im trying to get the difference between 2 differente dates in minutes, but is not outputting correctly.
Ex:
$then = "2017-01-23 18:21:24";
//Convert it into a timestamp.
$then = strtotime($then);
//Get the current timestamp.
$now = time();
//Calculate the difference.
$difference = $now - $then;
//Convert seconds into minutes.
$minutes = floor($difference / 60);
echo $minutes;
Is outputting 611 minutes, and is wrong since from "2017-01-23 18:21:24" to "2017-01-24 12:36:24" it past much more than 611 minutes. Is my code incorrect?
Try to set your default timezone
date_default_timezone_set('Europe/Copenhagen');
Ofc change Europe/Copenhagen for the one that suits your needs.
If you are using or able to use PHP 5.3.x or later, you can use its DateTime object functionality:
$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');
You can play with the format in a variety of ways, and once you have dates in DateTime objects, you can take advantage of a lot of different functionality, for example comparison via normal operators. See the manual for more: http://us3.php.net/manual/en/datetime.diff.php
I've checked your code it works perfectly So if have any doubt see your result
But you got wrong, so to ignore this set your timezone.

PHP Adding 15 minutes to Time value

I have a form that receives a time value:
$selectedTime = $_REQUEST['time'];
The time is in this format - 9:15:00 - which is 9:15am. I then need to add 15 minutes to this and store that in a separate variable but I'm stumped.
I'm trying to use strtotime without success, e.g.:
$endTime = strtotime("+15 minutes",strtotime($selectedTime)));
but that won't parse.
Your code doesn't work (parse) because you have an extra ) at the end that causes a Parse Error. Count, you have 2 ( and 3 ). It would work fine if you fix that, but strtotime() returns a timestamp, so to get a human readable time use date().
$selectedTime = "9:15:00";
$endTime = strtotime("+15 minutes", strtotime($selectedTime));
echo date('h:i:s', $endTime);
Get an editor that will syntax highlight and show unmatched parentheses, braces, etc.
To just do straight time without any TZ or DST and add 15 minutes (read zerkms comment):
$endTime = strtotime($selectedTime) + 900; //900 = 15 min X 60 sec
Still, the ) is the main issue here.
Though you can do this through PHP's time functions, let me introduce you to PHP's DateTime class, which along with it's related classes, really should be in any PHP developer's toolkit.
// note this will set to today's current date since you are not specifying it in your passed parameter. This probably doesn't matter if you are just going to add time to it.
$datetime = DateTime::createFromFormat('g:i:s', $selectedTime);
$datetime->modify('+15 minutes');
echo $datetime->format('g:i:s');
Note that if what you are looking to do is basically provide a 12 or 24 hours clock functionality to which you can add/subtract time and don't actually care about the date, so you want to eliminate possible problems around daylights saving times changes an such I would recommend one of the following formats:
!g:i:s 12-hour format without leading zeroes on hour
!G:i:s 12-hour format with leading zeroes
Note the ! item in format. This would set date component to first day in Linux epoch (1-1-1970)
strtotime returns the current timestamp and date is to format timestamp
$date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
$date=date("h:i:sa",$date);
This will add 15 mins to the current time
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
get After 20min time and date
function add_time($time,$plusMinutes){
$endTime = strtotime("+{$plusMinutes} minutes", strtotime($time));
return date('h:i:s', $endTime);
}
20 min ago Date and time
date_default_timezone_set("Asia/Kolkata");
echo add_time(date("Y-m-d h:i:sa"),20);
In one line
$date = date('h:i:s',strtotime("+10 minutes"));
You can use below code also.It quite simple.
$selectedTime = "9:15:00";
echo date('h:i:s',strtotime($selectedTime . ' +15 minutes'));
Current date and time
$current_date_time = date('Y-m-d H:i:s');
15 min ago Date and time
$newTime = date("Y-m-d H:i:s",strtotime("+15 minutes", strtotime($current_date)));
Quite easy
$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

Behavior of <?php echo date("H:i:s", 0);?>

I used :
<?php
echo date("H:i:s", $var_time_diff);
?>
to construct a time between two dates.. and in my head it was
$var_time_diff = 36000 = display 10:00:00 for 10 hours.
But in fact
<?php echo date("H:i:s", 0);?>
display 01:00:00 and not 00:00:00.
So we have
$date_a = "18:15:04";
$date_b = "23:15:04";
$diff = strtotime($date_b) - strtotime($date_a);
All is ok for the moment $diff is 5 hours but if we display date like this:
echo date("H:i:s", $diff);
it will be "06:00:00".
So something wrong with my php config or it's a normal behavior for php function date?
The date() function uses your current time zone. If you want to ignore your configured time zone, use date_default_timezone_set() or use gmdate().
You're in some timezone other than UTC. Try:
<?php
date_default_timezone_set('UTC');
echo date("H:i:s",0) . "\n";
I'm not sure why, but date outputs the current hour in your example, make a timestamp from your seconds first and it works. I'll be following this question for a deeper explanation though.
$date_a = "18:15:04";
$date_b = "23:15:04";
$diff = strtotime($date_b) - strtotime($date_a);
echo date("H:i:s", mktime(0,0,$diff));
edit: ah, so it adjusts to your current timezone, so does mktime, so the effect is negated.
use mktime, and min 1 for hour # $diff

check time for time difference in 24hr

In php i get the variable $date_time in this format -- 11-01-2010 20:48:25 . This time is GMT time. I have a 2 hour flexibility and if it exceeds 2 hours then i have to reject it. I am set in EST, but i want to do the check based on GMT only so that there is no errors in the time difference. How can i set to GMT in my php code and how do i check for the 2 hours flexible time difference? like for this example it is acceptable for any time between 11-01-2010 18:48:25 and 11-01-2010 22:48:25. Also will it be an issue if $date_time is 11-01-2010 23:48:23?
Clarification
I am doing a $date_time=$_GET['date_time'];. Then i need to check if this new $date_time if within 2 hours range of the current GMT time. if it is in the range, then i will proceed to execute that code, else i will show an error or do something else. I wanted to know how i am going to check this 2 hours range for this $date_time variable.
Here is a way how to convert your time format into a UNIX timestamp:
$date = strptime($date_time, "%m-%d-%Y %T");
$ut = mktime($date['tm_hour'], $date['tm_min'], $date['tm_sec'], 1 + $date['tm_mon'], $date['tm_mday'], 1900 + $date['tm_year']);
$now = time();
if($ut >= $now && $ut <= ($now + 7200)) { // 7200 = 2 * 60 * 60 seconds
// allowed
}
Reference: strptime, mktime, time.
Note: time() always returns the UNIX timestamp in UTC (regardless of time settings). So this assumes that the $date_time timestamp is a GMT time.
Working example (of course you have to provide a valid GMT time for $date_time).
Note 2: If the input time is not in GMT, you can set the timezone with date_default_timezone_set (affects mktime but not time).
Working example (change time and timezone accordingly)
If PHP >= 5.3 (you've got a seriously weird format BTW):
date_default_timezone_set('EST');
$inputtime = DateTime::createFromFormat('m-d-Y H:i:s','11-01-2010 20:48:25',new DateTimeZone("GMT"));
$diff = $inputtime->getTimestamp() - time();
if(abs($diff) > 7200){
//more then 2 hours difference.
}
If you run on PHP > 5.3, you can use DateTime for this :
$my_date = "11-01-2010 20:48:25";
$date = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_upper = DateTime::createFromFormat('m-d-Y H:i:s', $my_date);
$date_lower->sub(new DateInterval('PT2H'));
$date_upper->add(new DateInterval('PT2H'));
var_dump($date >= $date_lower && $date <= $date_upper); // bool(true)
I find it more readable.
You can also use another timezone if necessary, check the third argument of createFromFormat.
I suggest you to never pass times and dates with format string. Just convert it later. You just pass the timestamp as a get variable and then you format it in the script.
It's the best solution and also the cleanest.
Then use the following code:
$flexibility = X seconds;
if ($date_time < time() - $flexibility or $date_time > time() + $flexibility)
{ /*Error*/ }

Determining elapsed time

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;

Categories