Get only time from a string of more than one dateTime - php

I have a string which gets the dateTime as a GROUP from the database, so I get something like this
2017-10-20 05:00:00,2017-10-20 09:00:00,2017-10-20 07:00:00,2017-10-20 13:30:00,2017-10-20 16:00:00,2017-10-20 13:00:00,2017-10-20 06:00:00,2017-10-20 09:30:00,2017-10-20 10:30:00,2017-10-20 15:30:00,2017-10-20 17:00:00
Note that all of the dates are the same, i.e., 2017-10-20. Since I don't need to worry about the different dates. All I want is to simply extract the time from this string, and print it nicely like this
05:00, 09:00, 07:00, 13:30, 16:00 //and so on
I don't want the seconds, it would be unnecessary.
I tried using PHP's strtotime() function but it fails and gives 00:00:00 instead.
Any ideas? I am using Laravel as a templating engine.

Do it within your SQL statement.
SELECT TIME_FORMAT(`dateColumn`, '%H:%i') FROM ...

Step by step:
$dateTimes = '2017-10-20 05:00:00,2017-10-20 09:00:00,2017-10-20 07:00:00,2017-10-20 13:30:00,2017-10-20 16:00:00,2017-10-20 13:00:00,2017-10-20 06:00:00,2017-10-20 09:30:00,2017-10-20 10:30:00,2017-10-20 15:30:00,2017-10-20 17:00:00';
$dateTimesArray = explode(',', $dateTimes);
$timesArray = [];
foreach($dateTimesArray as $dateTime) {
$timesArray[] = date('H:i', strtotime($dateTime));
}
$times = join(',', $timesArray);

<?php
$tGroup = "2017-10-20 05:00:00,2017-10-20 09:00:00,2017-10-20 07:00:00,2017-10-20 13:30:00,2017-10-20 16:00:00,2017-10-20 13:00:00,2017-10-20 06:00:00,2017-10-20 09:30:00,2017-10-20 10:30:00,2017-10-20 15:30:00,2017-10-20 17:00:00";
$retVal = "";
$dates = explode(",", $tGroup);
foreach ($dates as $date) {
$time = date('H:i', strtotime($date));
// use this if you want to print AM/PM format
//$time = date('h:i A', strtotime($date));
$retVal .= $time . ", ";
}
echo trim($retVal," ,");

Related

Get difference between two dates in hours inside foreach loop

What i want is to get difference between start and ends dates for user. there are 3 dates for a user which has start date and end dates. and all dates coming from database when i try i am unable to get desired result which is to get differences between dates such as 2 days, 3 days, 4 days from list of dates, and no error is showing.
My Code
<?php
$eid = $_SESSION['eid'];
$sql = "SELECT empid,ToDate,FromDate from tblleaves where empid=:eid";
$query = $dbh->prepare($sql);
$query->bindParam(':eid',$eid,PDO::PARAM_STR);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0) {
foreach($results as $result)
{
$diff = date_diff($result->ToDate, $result->FromDate);
echo $diff->format("%h Hours");
htmlentities($result->FromDate));
}
}
?>
Database:
Is there anything outputted by your echo statement?
As fat as PHP is concerned the value returned by mysql/pdo is a string.
You have at least two options.
From the first example in the php docs for date_diff:
https://www.php.net/manual/en/datetime.diff.php
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Notice that they convert the date string to a date object first.
Then you can use date_diff or
$someDateObj->diff($dateObjTwo)
An alternative that works just as well is to select the date fields as a unix timestamp, then subtract both timestamps and convert the remaining absolute value to time in the format you wish. I may follow up with an example of that later.
edit - answering on my tiny phone so I missed the date format issue
Your date format in database is wrong, you have to fix that first by replacing the / with - eg.str_replace('/', '-', $result->ToDate))
then you have to convert the date to correct format like Y-m-d, after that you can check the difference, here is the solution for you
$to = date('Y-m-d', strtotime(str_replace('/', '-', $result->ToDate)));
$from = date('Y-m-d', strtotime(str_replace('/', '-', $result->FromDate)));
$datediff = strtotime($to) - strtotime($from);
echo abs(round($datediff / (60 * 60 * 24)));
if you want the difference in hours you can try the below code
$hourdiff = abs(round(($datediff)/3600, 1));
I hope this will help you
I ended up with this code this definitely help others.
$eid=$_SESSION['eid'];
$sql = "SELECT empid,ToDate,FromDate from tblleaves where empid=:eid";
$query = $dbh->prepare($sql);
$query->bindParam(':eid',$eid,PDO::PARAM_STR);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
if($query->rowCount() > 0)
{
foreach($results as $result)
{
$to = date('Y-m-d', strtotime(str_replace('/', '-', $result->ToDate)));
$from = date('Y-m-d', strtotime(str_replace('/', '-', $result->FromDate)));
$hours = round(abs(strtotime($from) - strtotime($to))/60/60).'<br>';
$sum+=$hours;
}
echo '<h5>'.$sum.' Hours '.'</h5>';
}
?>

Verifiying 2 date to make sure they're valid dates

I am working with a date which is formatted like so:
25/02/1994 - 15/03/2000
To get each date I am using the explode function to separate each date between dash
$newdate = explode("-",$olddate);
Now my problem is, if it was just one date I could split it up in to 3 parts, the day, month, year and use the checkdate function to validate the month, but because I am using explode I cannot split it up like that (to my knowledge)
What would be the best way to validate the date for legitimacy?
You have a good start, after you exploded your string by -, just simply loop through each date with array_reduce() and reduce it to 1 value.
In the anonymous function you just explode() each date and check with checkdate() if it is a valid date, e.g.
<?php
$str = "25/02/1994 - 15/03/2000";
$dates = explode("-", $str);
if(array_reduce($dates, function($keep, $date){
list($day, $month, $year) = array_map("trim",explode("/", $date));
if(!checkdate($month, $day, $year))
return $keep = FALSE;
return $keep;
}, TRUE)) {
echo "all valid dates";
}
?>
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$first_date = explode("/", trim($date_array[0]));
$second_date = explode("/", trim($date_array[1]));
if(checkdate($first_date[1],$first_date[0],$first_date[2])){
//do stuff
}
if(checkdate($second_date[1],$second_date[0],$second_date[2])){
//do stuff
}
or, what Daan suggested using the DateTime object.
$date = '25/02/1994 - 15/03/2000';
$date_array = explode("-", $date);
$date1 = DateTime::createFromFormat('j-M-Y', $date_array[0]);
$date2 = DateTime::createFromFormat('j-M-Y', $date_array[1]);
if($date1){
//do stuff
}
if($date2){
//do stuff
}

Comparing Date from PHP to MYSQL, strtotime not working

I have a DATE field on my MySQL table. Let's say the value is 2015-05-05.
I would like to check if the current time is before or after that.
This is my code:
foreach ($row as $row)
{
$ExpDate = strtotime($row['exp_date']);
$Today = strtotime(date("Y-m-d"));
echo $Today . ' - ' . $ExpDate;
if ($Today > $ExpDate)
{
exit('<M>LicenseExpired<M>');
}
}
The problem is that it's not working. The value of exp without strtotime is 2015-05-05. It I add the strtotime, the value becomes an empty string.
How am I able to solve this problem or what would be a good way to compare dates in PHP?
When comparing dates in MySQL there is no reason to take the extra step and use string_to_time(). The below example should work just fine. The format of MySQL DATE is designed in such a way that comparisons of this nature work naturally without any extra steps needed.
foreach ($row as $row)
{
$ExpDate = $row['exp_date'];
$Today = date("Y-m-d");
echo $Today . ' - ' . $ExpDate;
if ($Today > $ExpDate)
{
exit('<M>LicenseExpired<M>');
}
}
try this
foreach ($row as $row)
{
$ExpDate = new DateTime($row['exp_date']);
$Today = new DateTime(date("Y-m-d"));
$interval = $ExpDate->diff($Today);
//echo $interval->format('%R%a days'); <--- to diffenernce by days.
if ($interval > 0)
{
exit('<M>LicenseExpired<M>');
}
}

Start Date and Start Time Less than End Date and End Time Validation

Start Time, End Date and End Time variables.
The Date Variables are formatted yyyy-mm-dd
The Time Variables are formatted hh-mm (however only on hour numbers are usable, e.g Minutes is always 00)
I can insert these variables into my database no problem, however before I do I want to check that the start date and time is before the end date and time. I know how to check if the time is earlier, and the date is earlier, but I cannot check the time and date together and I would appreciate any help?
$_POST['start_time']
$_POST['end_time']
$_POST['start_date']
$_POST['end_date']
are the variables and how I am grabbing them.
Use DateTime objects to make life simple for yourself:
<?php
// assuming the following values...
$_POST['start_time'] = '06:00';
$_POST['end_time'] = '10:00';
$_POST['start_date'] = '2012-01-01';
$_POST['end_date'] = '2013-06-02';
//set up two DateTime objects
$start = DateTime::createFromFormat('Y-m-d H-i', $_POST['start_date'] . ' ' . $_POST['start_time']);
$end = DateTime::createFromFormat('Y-m-d H-i', $_POST['end_date'] . ' ' . $_POST['end_time']);
// check if they're valid
if ($start < $end) {
echo 'We are good...';
} else {
echo 'Something bad happened...';
}
Bear in mind that this assumes that your $_POSTed values are valid. If you haven't sanitized them already, wrap it in a try/catch at least.
function getTime ($ymd, $hi) {
return strtotime($ymd." ".$hi);
}
if (getTime($_POST['start_date'], $_POST['start_time']) < getTime($_POST['end_date'], $_POST['end_time'])) {
echo "Ok!";
}
Simply convert it to an Unix-timestamp and then compare.
I would use DateTime::createFromFormat() for it. Like this:
$start = DateTime::createFromFormat('Y-m-d H-i',
$_POST['start_date'] . ' ' . $_POST['start_time']);
Try exploding the arrays and then using mktime() function to pass the date to seconds. Then, just compare both dates, the bigger in seconds is the later.
list($strHour, $strMin) = explode('-', $_POST['start_time']);
list($endHour, $endMin) = explode('-', $_POST['end_time']);
list($strYear, $strMonth, $strDay) = explode('-', $_POST['start_date']);
list($endYear, $endMonth, $endDay) = explode('-', $_POST['end_date']);
$startSeconds = mktime($strHour, $strMin, 0, $strMonth, $strDay, $strYear);
$endSeconds = mktime($endHour, $endMin, 0, $endMonth, $endDay, $endYear);
if ($startSeconds > $endSeconds) {
echo 'Start is bigger';
}

Get the year from specified date php

I have a date in this format 2068-06-15. I want to get the year from the date, using php functions. Could someone please suggest how this could be done.
$date = DateTime::createFromFormat("Y-m-d", "2068-06-15");
echo $date->format("Y");
The DateTime class does not use an unix timestamp internally, so it han handle dates before 1970 or after 2038.
You can use the strtotime and date functions like this:
echo date('Y', strtotime('2068-06-15'));
Note however that PHP can handle year upto 2038
You can test it out here
If your date is always in that format, you can also get the year like this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
I would use this:
$parts = explode('-', '2068-06-15');
echo $parts[0];
It appears the date is coming from a source where it is always the same, much quicker this way using explode.
You can try strtotime() and date() functions for output in minimum code and using standard way.
echo date('Y', strtotime('2068-06-15'));
output: 2068
echo date('y', strtotime('2068-06-15'));
output: 68
public function getYear($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("Y");
}
public function getMonth($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("m");
}
public function getDay($pdate) {
$date = DateTime::createFromFormat("Y-m-d", $pdate);
return $date->format("d");
}
<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>
You can achieve your goal by using php date() & explode() functions:
$date = date("2068-06-15");
$date_arr = explode("-", $date);
$yr = $date_arr[0];
echo $yr;
That is it. Happy coding :)
Assuming you have the date as a string (sorry it was unclear from your question if that is the case) could split the string on the - characters like so:
$date = "2068-06-15";
$split_date = split("-", $date);
$year = $split_date[0];
$Y_date = split("-","2068-06-15");
$year = $Y_date[0];
You can use explode also
You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there
$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}

Categories