php - Calculate different from string - php

I have 2 string like this "2018/04/10-14:54:55" and "2018/04/10-14:56:10".
How can I calculate different between them? I've used strtotime to change the string to date but it gives the wrong value.
Please help me with this.
Thank you

<?php
$time1 = '2018/04/10-14:54:55';
$time2 = '2018/04/10-14:56:10';
$format = 'Y/m/d-H:i:s';
$t1 = DateTime::createFromFormat($format, $time1);
$t2 = DateTime::createFromFormat($format, $time2);
echo "time1" . $t1->format('Y-m-d H:i:s') . "<br/>";
echo "time2" . $t2->format('Y-m-d H:i:s') . "<br/>";
$difference = $t1->diff($t2);
echo $difference->format('%s%a secs');
You can use specific format to create a datetime ojbect, after that you can use diff function to get the difference.

Please try this code.
function time_difference($time_1, $time_2, $limit = null)
{
$val_1 = new DateTime($time_1);
$val_2 = new DateTime($time_2);
$interval = $val_1->diff($val_2);
$output = array(
"year" => $interval->y,
"month" => $interval->m,
"day" => $interval->d,
"hour" => $interval->h,
"minute" => $interval->i,
"second" => $interval->s
);
$return = "";
foreach ($output AS $key => $value) {
if ($value == 1)
$return .= $value . " " . $key . " ";
elseif ($value >= 1)
$return .= $value . " " . $key . "s ";
if ($key == $limit)
return trim($return);
}
return trim($return);
}
$time1 = '2018/04/10 14:54:55';
$time2 = '2018/04/10 14:56:10';
$resp = time_difference ($time1, $time2);
echo $resp;
output:
1 minute 15 seconds

This is an example, I have explained the details in the code itself:
<?php
date_default_timezone_set("Asia/Tehran"); //Set your timezone to avoid warnings in PHP error_log
// Use '/' for American date format and use '-' for Europian date format
// Use 'T' instead of '-'
$time_1 = strtotime( str_replace('-', 'T', "2018/04/10-14:54:55") ); //Replace '-' to 'T' to get "2018/04/10T14:54:55"
$time_2 = strtotime( str_replace('-', 'T', "2018/04/10-14:56:10") ); //Replace '-' to 'T' to get "2018/04/10T14:56:10"
$diff = $time_2 - $time_1;
echo $diff; // in seconds
?>
I hope it helps.

Related

How to split time value in PHP?

I have these time value from HTML form using timepicker js.
I want to split the value into three (3) variables which is $hour, $minute and $period.
The problem is I can't split 'AM' or 'PM' value into another variable.
$minute hold the value "00 PM". I want AM or PM store into another variable call $period
What I have done so far as code below.
Time.php
<?php
// $btArray = explode(':', $_POST['app_time']);
$btArray = explode(':', '11:00 PM');
$hour = strlen(trim($btArray[0])) > 1 ? trim($btArray[0]) : '0' . trim($btArray[0]);
$minute = trim($btArray[1]);
$period = trim($btArray[2]);
$query = "UPDATE TABLE
SET
BOOK_TIME = '" . $hour . ":" . $minute . "',
TIME_PERIOD = '" . $period ."'
WHERE
TRACK_NUM = ''
";
?>
My goal is to split the value so I can store it into database.
Appreciate if someone can help me to solve this problem.
Thanks.
$btArray= "7:00 am";
preg_match("/([0-9]{1,2}):([0-9]{1,2}) ([a-zA-Z]+)/", $btArray, $match);
$hour = $match[1];
$min = $match[2];
$period = $match[3];
$query = "UPDATE TABLE
SET
BOOK_TIME = '" . $hour . ":" . $minute . "',
TIME_PERIOD = '" . $period ."'
WHERE
TRACK_NUM = ''
";
Try this,
$time = '11:00 PM';
//first remove right two char
$period = substr($time, -2, 2);
//remove that string from main string
$newTime = str_replace($period, "", $time);
//convert remaining string to array
$btArray = explode(':', $newTime);
//check hour string length and concate 0
$hour = (strlen($btArray[0]) > 1) ? $btArray[0] : '0'.$btArray[0];
$mint = $btArray[1];
echo $hour.'<pre>';
echo $mint.'<pre>';
echo $period.'<pre>';
die;
Output:
11
00
PM
I would rather suggest to use substr() function as the parameters like: hour, minute, seconds are fixed.
First need to check whether the string length of 8.
Then, get parameters depending upon their positions.
If your date format is constant.
<?php
$str = '11:00 PM';
if (strlen($str) == 8) {
$hour = substr($str, 0, 2);
$minute = substr($str, 3, 2);
$period = substr($str, 6, 2);
}
echo '<pre>';print_r('Hour: '. $hour);echo '</pre>';
echo '<pre>';print_r('Minute: '. $minute);echo '</pre>';
echo '<pre>';print_r('AM/PM: '. $period);echo '</pre>';
Output:
Hour: 11
Minute: 00
AM/PM: PM
Working Demo:
You can try below code for your desire output.
$btArray = explode(':', '11:00 PM');
$hour = strlen(trim($btArray[0])) > 1 ? trim($btArray[0]) : '0' . trim($btArray[0]);
$minute_period_array = explode(' ', $btArray[1]);
$minute = trim($minute_period_array[0]);
$period = trim($minute_period_array[1]);
echo 'Hour - ' . $hour . '<br/>';
echo 'Minute - ' . $minute . '<br/>';
echo 'Period - ' . $period . '<br/>';
Output :
Hour - 11
Minute - 00
Period - PM
If you will get the input value always in the same format, you can go this way:
$input = '8:05 PM';
list($hour, $minute, $period) = explode(' ', str_replace(':', ' ', $input), 3);
// And then clean the variables
$hour = str_pad($hour, 2, '0', STR_PAD_LEFT);
$minute = str_pad($minute, 2, '0', STR_PAD_LEFT);
$period = strtoupper(trim($period));
// $hour -> 08, $minute -> 05, $period -> PM

How to get the start date and end date when the year number and month number are known in php

I have the year number (ex: 2018) and the month number (Ex:04). I want to get the starting date and the ending date for that month. like
2018-04-01 and 2018-04-30
try this
$year = 2018;
$month = 4;
$date_start = date('Y-m-d', strtotime(date($year.'-'.$month).' first day of this month'));
$date_end = date('Y-m-d', strtotime(date($year.'-'.$month).'last day of this month'));
echo $date_start . ' and ' . $date_end;
$months_array = $this->getting_particular_months_dates($start_day_of_year, $end_day_of_year);
$arra1=array();
foreach ($months_array as $K => $v)
{
$year=explode( '-',$v['month'])[1];
$month=explode( '-',$v['month'])[0];
$arra1[]=$this->get_month_dates((int)$year,(int)$month);
}
return $arra1;
public function getting_particular_months_dates($year_start_date, $year_end_date)
{
$month_array = array();
$date1 = $year_start_date;
$date2 = $year_end_date;
$output = [];
$time = strtotime($date1);
$last = date('m-Y', strtotime($date2));
do {
$month = date('m-Y', $time);
$total = date('t', $time);
$output[] = [
'month' => $month,
'total' => $total,
];
$time = strtotime('+1 month', $time);
} while ($month != $last);
$month_array = $output;
return $month_array;
}
public function get_month_dates($year, $month)
{
$date_start = date('Y-m-d', strtotime(date($year . '-' . $month) . ' first day of this month'));
$date_end = date('Y-m-d', strtotime(date($year . '-' . $month) . 'last day of this month'));
$a = array('first_day' => $date_start, 'last_day' => $date_end);
return $a;
}

Checking hour and minutes inside datetime

Is there a way to see inside this function if $hours and $minutes are any other than 00:00, so that if they arent, i wont show the time?
public static function datetimedutch($date)
{
if ($date != '')
{
list($newdate, $time) = explode(' ', $date);
list($date_year, $date_month, $date_day) = explode('-', $newdate);
list($hours, $minutes, $seconds) = explode(':', $time);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maandnr = date("n", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
$maand_dag = date("j", mktime($hours, $minutes, $seconds, $date_month,$date_day,$date_year));
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
}
}
This should do it :)
function datetimedutch($date)
{
if (!empty($date))
{
$someDate = strtotime($date);
$hours = date('H',$someDate);
$minutes = date('i',$someDate);
$dag = array('zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag');
$maand = array('maand','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december');
$weekdag = date("w", $someDate);
$maandnr = date("n", $someDate);
$maand_dag = date("j", $someDate);
if($hours>0 || $minutes>0) {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr] . ' ' . $hours . ':' . $minutes;
} else {
return $dag[$weekdag] . ' ' . $maand_dag . ' ' . $maand[$maandnr];
}
} else {
return false;
}
}
echo datetimedutch('2014-05-15 12:39:06');
echo "<br />";
echo datetimedutch('2014-05-15 00:00:06');
I really recommend using automated way of getting locale formatted date, for example:
function formatDateInDutch($date = null) {
$date = strtotime($date);
$currentLocale = setlocale(LC_TIME, 0);
switch (PHP_OS){
case 'WIN':
case 'WINNT':
setlocale(LC_TIME, 'Dutch');
break;
case 'LINUX':
default:
setlocale(LC_TIME, 'nl_NL');
}
// format: http://pl1.php.net/manual/en/function.strftime.php
$ret = strftime('%A %w %B %m', $date);
// has minutes, display hour:minute
if ((int)date('i', $date) != 0) {
$ret .= ' '.date('H:i', $date);
// has only hours
} elseif ((int)date('H', $date) != 0 AND (int)date('i', $date) == 0) {
$ret .= ' '.date('H', $date);
}
// restore default locale
setlocale(LC_TIME, $currentLocale);
return $ret;
}
function formatDateInDutchBetter($date = null){
$date = new DateTime($date, new DateTimeZone('Europe/Amsterdam'));
// format: http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details
$formatPattern = 'EEEE e LLLL dd ';
// NOTE: $date->format and IntlDateFormatter format patterns ARE DIFFERENT!!!
// if datetime has minutes then display hour:minutes
if ((int)$date->format('i') != 0) {
$formatPattern .= 'HH:mm';
// if datetime has only minutes display minutes
} elseif ((int)$date->format('H') != 0 AND (int)$date->format('i') == 0) {
$formatPattern .= 'HH';
}
$formattedDate = IntlDateFormatter::formatObject($date, $formatPattern, 'nl_NL');
return $formattedDate;
}
print formatDateInDutch(date('Y-m-d H:m:s'));
print '<hr>';
print formatDateInDutchBetter(date('Y-m-d H:m:s'));
And I really recommend second approach: using internationalization extension from PHP. It requires enabling extension but it is platform independent and it is very easy to add/change other locales.

Format MySql time for display to client, undefined offset error

I have a function that is supposed to calculate how long ago an article was written and then return whatever value it has got when it is called. However I get the notice message which is an error I dnt want to supress but solve.
function getTimeAgo($date,$granularity=1){
$values = explode(" ",$date);
$time = new DateTime('now', new DateTimeZone('UTC'));//GET CURRENT UTC TIME
$date = $values[2] . "-" . $values[1] . "-" . $values[5] . " " . $values[3];
$difference = strtotime($time->format('Y-m-d H:i:s')) - strtotime($date);
$retval='';
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'min' => 60,
'sec' => 1);
foreach ($periods as $key => $value) {
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' ';
$retval .= (($time > 1) ? $key.'s' : $key);
$granularity--;
}
if ($granularity == '0') { break; }
}
return $retval.' ago';
}
}
ERROR: is that there is an undefined offset [2] , [1], [5] and [3] at this particular location
$date = $values[2] . "-" . $values[1] . "-" . $values[5] . " " .
Your function accepts $date value as 2013-12-01 08:16:32
so doing
$values = explode(" ",$date);
will give you array as
$values[0] = 2013-12-01
$values[1] = 08:16:32
So
$date = $values[2] . "-" . $values[1] . "-" . $values[5] . " "
will not have indexes 2,5....
In case the function receives an empty data, then doing explode will return all invalid index.
You can use the $date from the argument directly inside
$difference = strtotime($time->format('Y-m-d H:i:s')) - strtotime($date);
if the passed value is in the format 2013-12-01 08:16:32

Text time to numbers

I have multiple rows with time
"42 sec"
"1 min"
"2 h 32 min"
Is it possible to convert this to
"00:00:42"
"00:01:00"
"02:32:00"
with php?
PHP's strtotime() is a useful function that can convert a string representation of a time into a unix timestamp. From that we can then convert the time into any format we like.
However, your original time strings aren't in a format that strtotime() can handle directly. eg. 'h' must be 'hour'. But we could perhaps replace these before passing to strtotime() if your data is consistent.
Note we attempt to convert the original time relative to 0, not the current time.
$rawTimes = array ('42 sec', '1 min', '2 h 32min');
foreach ($rawTimes as $rawTime) {
// Convert into a format that strtotime() can understand
$rawTime = str_replace('h','hour',$rawTime);
echo '"'.$rawTime.'" = "'.gmdate('H:i:s',strtotime($rawTime,0)).'"'."\n";
}
Will output:
"42 sec" = "00:00:42"
"1 min" = "00:01:00"
"2 hour 32min" = "02:32:00"
Note that strtotime() understands 'sec', 'second', 'min', 'minute' and 'hour'. And appears to handle space or no space OK eg. '32min' or '32 min' is handled OK.
Not the cleanest solution, but it works for your three cases:
<?
$time[] = "42 sec";
$time[] = "1 min";
$time[] = "2 h 32min";
$seconds = '/([\d]{1,})\s?sec/';
$minutes = '/([\d]{1,})\s?min/';
$hours = '/([\d]{1,})\s?h/';
foreach( $time as $t )
{
echo '<br />';
preg_match( $hours, $t, $h );
$hour = $h[1];
if( $hour )
{
if( strlen( $hour )<2 )
$hour = '0' . $hour;
}
else
$hour = '00';
preg_match( $minutes, $t, $m );
$min = $m[1];
if( $min )
{
if( strlen( $min )<2 )
$min = '0' . $min;
}
else
$min = '00';
preg_match( $seconds, $t, $s );
$sec = $s[1];
if( $sec )
{
if( strlen( $sec )<2 )
$sec = '0' . $sec;
}
else
$sec = '00';
echo $hour . ':' . $min . ':' . $sec;
}
?>
Outputs:
00:00:42
00:01:00
02:32:00
I'm pretty sure there's a better solution, but that one works.
function timetotime($str) {
$match = null;
if (preg_match("/(\d+)(\s?)h/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result = "0{$h}:";
else
$result = "{$h}:";
} else
$result = "00:";
if (preg_match("/(\d+)(\s?)min/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result .= "0{$h}:";
else
$result .= "{$h}:";
} else
$result .= "00:";
if (preg_match("/(\d+)(\s?)sec/", $str, &$match)) {
$h = $match[1];
if ($h < 10)
$result .= "0{$h}";
else
$result .= "{$h}";
} else
$result .= "00";
return $result;
}
http://php.net/manual/en/function.strtotime.php
<?php
$dates = array("42 sec", "1 min", "2 hour 32 min"); // normalise last item
foreach($dates as $d)
printf("%5s - %s\n", $d, nSecs($d));
function nSecs($date)
{
$t = strtotime("+1 day $date");
return $t - strtotime("+1 day");
}
?>
If you can normalise the h => hour, it's not so bad.

Categories