Find the difference between start date and end date in php using mktime and explode functions
Find the difference between start date and end date in php using mktime and explode functions
function find_difference($start_date,$end_date){
list($date,$time) = explode(" ",$start_date);
if($time == NULL){$time = '00:00:00';}
$startdate = explode("-",$date);
$starttime = explode(":",$time);
list($date,$time) = explode(" ",$end_date);
if($time == NULL){$time = '00:00:00';}
$enddate = explode("-",$date);
$endtime = explode(":",$time);
//Get unix timestamp in seconds
$secons_dif = mktime($endtime[0],$endtime[1],$endtime[2],$enddate[1],$enddate[2],$enddate[0]) - mktime($starttime[0],$starttime[1],$starttime[2],$startdate[1],$startdate[2],$startdate[0]);
//We will return it in seconds, minutes, hours, days, weeks, months, years
//put the word floor before () to round to the nearest whole number.
$seconds = $secons_dif;
$minutes = ($secons_dif/60);
$hours = ($secons_dif/60/60);
$days = ($secons_dif/60/60/24);
$weeks = ($secons_dif/60/60/24/7);
$months = ($secons_dif/60/60/24/7/4);
$years = ($secons_dif/365/60/24/60);
return $days;
}
[Google Ads]
Using mktime() without arguments is not supported, and will result in an ArgumentCountError. time() can be used to get the current timestamp.
Syntax:
mktime(hour, minute, second, month, day, year)
Parameters:
mktime(hour (0-23), minute(0-59), second (0-59), month (1-12), day(1-31), year(four-digit))
Examples:
-Create a Unix timestamp for January
$timestamp = mktime(12, 0, 0, 1, 1, 2022);
echo $timestamp;
-Create a Unix timestamp for the current time
$hour = date('H');
$minute = date('i');
$second = date('s');
$month = date('n');
$day = date('j');
$year = date('Y');
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
echo $timestamp;
Points to consider:
1. `mktime()` assumes the input values are in the local timezone.
2. If no arguments are provided, `mktime()` returns the current Unix timestamp.
3. Be cautious when using `mktime()` with daylight saving time (DST) transitions.
PHP's explode() function:
Syntax:
explode(separator, string, limit)
Parameters:
1. separator - as a (string): The delimiter to split the string.
2. string - as a (string): The input string to be split.
3. limit -(int, optional): The maximum number of characters to be return.
Output :
Returns Array of strings
Examples:
Split a string by commas
$string = "apple,banana,cherry";
$fruits = explode(",", $string);
print_r($fruits);
Output:
Array ( [0] => apple [1] => banana [2] => cherry )
Notes to Remember:
1. explode() returns an array, even if only one element is found.
2. If limit is negative, explode() returns all elements except the last -limit -elements.
3. If separator is not found, explode()returns the original string as the only element.
[Google Ads]