How to display time in PHP by date() function - php

I get the value 9.0 from a CSV file that I would like to print as the time 09:00:00
If i try
<?php
$time = 9.01;
echo date('H:i:s', strtotime($time));
It displays 09:01:00.
But if I try
<?php
$time = 9;
echo date('H:i:s', strtotime($time)); or echo date('H:i:s', strtotime(9.00));
It displays 01:00:00.
I want to get time 09:00:00.

Please try this
$time = 9;
echo date( 'H:i:s', strtotime( number_format($time, 2)));

This is how to fill a date variable with any value you need:
<?php
$d=mktime(9, 0, 0);
echo "Created date is " . date("h:i:s", $d);
?>
See the documentation of mktime

It appears the main issue is the import CSV has a malformed date. Assuming you cannot change it and that the value is {hours}.{minutes}. Minutes not being a fraction but a value between 0 - 60. Otherwise, this will need adjusting to convert the fraction of an hour into minutes.
I'm using the DateTime class to achieve this.
$value = 9.1;
if (is_float($value)) {
$hour = (int)$value;
$minute = number_format(($value - floor($value)) * 100);
$date = new DateTime();
$date->setTime($hour, $minute);
} else {
$date = new DateTime($value);
}
$formattedTime = $date->format('H:i');
echo $formattedTime . "\n";

For 12 hours Formate
echo date("h:i:s a");
For 24 hours Formate
echo date("H:i:s");

Related

PhP date time addition

I have 2 variables.
The first -> ("01:10:00")(string);
The second -> ("2021-02-23 16:30:00")(string)
I want to add the two to be like "2021-02-23 17:40:00".
How can I accomplish this with PHP?
The answers was very much appreciated, thanks everyone.
You can do it by first exploding the time to add (first variable), then you finally add the exploded information to the date (second variable) using function strtotime:
<?php
$firstVar = "01:10:00";
list($hours, $minutes, $seconds) = explode(":", $firstVar);
$secondVar = "2021-02-23 16:30:00";
echo date('Y-m-d H:i:s',strtotime('+'. $hours .' hour +'. $minutes .' minutes +'. $seconds .' seconds',strtotime($secondVar)));
?>
You can do this:
<?php
$newtimestamp = strtotime('2021-02-23 16:30:00 + 70 minute');
// OR $newtimestamp = strtotime('2021-02-23 16:30:00 + 1 hour + 10 minute');
echo date('Y-m-d H:i:s', $newtimestamp); // Output: 2021-02-23 17:40:00
Anyway, if you need to convert HH:MM:SS to minutes, you can use the following function:
<?php
function minutes($time) {
$time = explode(':', $time);
return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}
echo minutes('01:10:00'); // Output: 70
So finally you can do:
<?php
$datetime = '2021-02-23 16:30:00';
$add = minutes('01:10:00');
$newtimestamp = strtotime("$datetime + $add minute");
echo date('Y-m-d H:i:s', $newtimestamp);
function minutes($time) {
$time = explode(':', $time);
return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}
A solution with DateTime. The time is converted into seconds and added using the modify method.
$timeArr = explode(':',"01:10:00");
$seconds = ($timeArr[0]*60 + $timeArr[1]) *60 + $timeArr[2];
$dateTime = date_create("2021-02-23 16:30:00")->modify($seconds." Seconds");
echo $dateTime->format("Y-m-d H:i:s");
This becomes even easier with the external class dt. This class has an addTime() method.
$dt = dt::create("2021-02-23 16:30:00")->addTime("01:10:00");
echo $dt->format("Y-m-d H:i:s"); //2021-02-23 17:40:00

How to sum hours with existing datetime in PHP?

I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');

PHP Adding minutes to Time value

How can I add time to a digit time value,
currently my code looks like this:
$time = strtotime('00:00:00');
$addTime = strtotime('+5 minutes', $time);
$addTime = date('h:i:s', $addTime);
If I echo $addTime I get this value:
1472680800147268110012:05:00
which is obviously wrong.
It should look like this:
00:05:00
Replace $addTime = date('h:i:s', $addTime); with $addTime = date('H:i:s', $addTime);
According to manual http://php.net/manual/en/function.date.php
H 24-hour format of an hour with leading zeros 00 through 23
It should be like this:
<?php
$addMinutes = 16;
$yourTime = new DateTime('08:02:00');
$yourTime->add(new DateInterval('PT' . $addMinutes . 'M'));
$result = $yourTime->format('H:i:s');
var_dump($result);
?>
Demo
Why don't simply write:
$time = strtotime('00:00:00');
$addTime = date('H:i:s', $time+5*60);

How to get difference of a time in seconds in PHP?

I have a database column with datatype "time" which stores 11:30:45. I have fetched this time in a variable say
$databasetime = 11:30:45
I want to declare a variable say $currenttime which will contain time just now. Like its 11:33:30 right now and another variable which will contain their difference in seconds like
$timediff = $currenttime - $databasetime;
echo $timediff;
I am trying $currenttime = time(); but I am not getting the result which I desire. I want $timediff = 165 but when I echo time(), I am getting a very big value.
$databasetime = strtotime('11:30:45');
$curtime = time();
echo $curtime - $databasetime;
You can do it in the following way:
$databasetime = '11:30:45';
$time1 = strtotime($databasetime);
$time2 = strtotime('now');
$diff = $time2 - $time1;
echo 'your difference: '.date('H:i:s', $diff);
$datetime1 = new DateTime('10:35:56 2013-11-17');
$datetime2 = new DateTime('10:35:50 2013-11-17');
$interval = $datetime1->diff($datetime2);
echo $interval->m . " Month " .$interval->d ." Days ". $interval->h . " Hours, " . $interval->i." Mintues, ".$interval->s." seconds <br/>";
<?php
$currentTime = time();
$futureDateTime = new DateTime('11:30:45'); // might want to specify a date and timezone, system TZ by default
$futureTime = $futureDateTime->format('U'); // get unix timestamp
$timeDiff = $futureTime-$currentTime;
?>
You use the DateTime 'OO' methods to return 'unix timestamp' integers directly
<?php
$now = new DateTime('now');
$date = new DateTime('11:30:45');
echo $now->getTimestamp() - $date->getTimestamp();
?>
Here is a simple example.
$databasetime = '11:30:45';
$timedif = abs(strtotime('now') - strtotime($databasetime));
echo $timedif; //echos the difference in seconds.
abs is used just to prevent neg numbers, which you may or may not want to do.
My problem is solved now. Actually all answers are right but the problem was due to the default time zone. I wanted Asia/Kolkata time zone but default European timezone apache was picking. That's why I was not getting my desired results.
So, I am finally using below code:
date_default_timezone_set('Asia/Kolkata');
$databasetime = strtotime('11:30:45');
$curtime = time();
echo $curtime - $databasetime;

PHP: add seconds to a date

I have $adate; which contains:
Tue Jan 4 07:59:59 2011
I want to add to this date the following:
$duration=674165; // in seconds
Once the seconds are added I need the result back into date format.
I don't know what I'm doing, but I am getting odd results.
Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.
If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>
Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);
Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
Do this:
$seconds = 1;
$date_now = "2016-06-02 00:00:00";
echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
I made this example for a timezone, but if you change some parts it may help you out:
$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;
Result:
2018/06/17 3:16:23========2018/06/17 3:15:53
It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string
I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time
This was my solution:
$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value
font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)
(1) https://secure.php.net/manual/en/function.date.php

Categories