this is my insert section the $total_minutes and $total_hour cant be inserted in the table
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$hour = $_POST['hour'];
$min = $_POST['min'];
$sec = $_POST['sec'];
$year1 = $_POST['year1'];
$month1 = $_POST['month1'];
$day1 = $_POST['day1'];
$hour1 = $_POST['hour1'];
$min1 = $_POST['min1'];
$sec1 = $_POST['sec1'];
$time_in = $year.'-'.$month.'-'.$day.' '.$hour.'-'.$min.'-'.$sec;
$time_out = $year1.'-'.$month1.'-'.$day1.' '.$hour1.'-'.$min1.'-'.$sec1;
$total_minutes = $total_min;
$total_hour = $total_hr;
$sql = "INSERT INTO time (year, month, day, hour, min, sec, year1, month1, day1, hour1, min1, sec1, time_in, time_out, total_minutes, total_hour)
VALUES
('$year','$month','$day','$hour','$min','$sec','$year1','$month1','$day1','$hour1','$min1','$sec1','$time_in','$time_out', '$total_minutes', '$total_hour')";
how can i add this in my table?
minutes
$datetime1 = strtotime($row['time_in']); //year-month-day hr:min:sec timein
$datetime2 = strtotime($row['time_out']); //year-month-day hr:min:sec timeout
$interval = abs($datetime2 - $datetime1);
$total_min = round($interval / 60);
$total_minutes = $total_min;
hour
function convertToHoursMins($total_minutes, $format = '%02d:%02d') {
if ($total_minutes < 1) {
return;
}
$hours = floor($total_minutes / 60);
$wmin = ($total_minutes % 60);
return sprintf($format, $hours, $wmin);
}
$total_hr = convertToHoursMins($total_minutes, '%02d hours %02d minutes');
$total_hour = $total_hr;
im new and i wanted a simple answer
Use MySQL TIMEDIFF() function to get the answer. Instead of PHP, MySQL Function gives the result in very easiest manner.
$datetime1 = strtotime($row['time_in']); //year-month-day hr:min:sec timein
$datetime2 = strtotime($row['time_out']); //year-month-day hr:min:sec timeout
$timeInterval = mysql_query("SELECT TIMEDIFF($datetime2, $datetime1)");
$timeArray = explode(":", $timeInterval);
Hope this may help you :)
You have to convert your datetime1 and datetime2 in this format first :
datetime1 = 2012-01-01 12:00:00;
datetime2 = 2012-01-02 13:00:00;
Then in my sql insert query directly insert value from following functions :
TIMESTAMPDIFF(HOUR, datetime2, datetime1) // For Hours Calculation
TIMESTAMPDIFF(MINUTE,datetime2, datetime1) // For Minutes Calculation
Hope this may help you :)
Related
I want to substract 2 dates and take the result in minutes like the code bellow gives me the answer i want.
$to_time = strtotime("2017-03-27 17:31:40");
$from_time = strtotime("2017-03-27 18:32:40");
echo "sunolo1: ".round(abs($to_time - $from_time) / 60,2). " minute";
But when i try to retrieve dynamically date from mysql using php it doesnt work it returns 0. (date in my table is in timestamp)
$d = new DateTime("now", new DateTimeZone("Europe/Athens"));
$dateM = $d->format("Y-m-j H:i:s");
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
while(mysqli_stmt_fetch($result)){
$sunolo_krathshs = round(abs($ddd - $dateM) / 60,2);
echo "sunoloo: ".$sunolo_krathshs;
}
You need to parse the value of $ddd to a DateTime object, since the easiest way would be to compare DateTime objects.
$date = new DateTime();
$ddd = $date->setTimestamp($ddd);
$sunolo_krathshs = round(abs($ddd - $d) / 60,2);
Please check this.
<?php
$datetime1 = new DateTime("2017-03-27 17:31:40");
$datetime2 = new DateTime("2017-03-27 18:32:40");
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
?>
Use strtotime function while passing the date values for calculation. Something like this:
$sunolo_krathshs = round(abs(strtotime($dateM) - strtotime($ddd)) / 60,2);
Using the DateTime class this can be quite simple
$result = mysqli_prepare($con, "SELECT date FROM mytable WHERE id= ? ");
mysqli_stmt_bind_param($result, 'i', $ids);
mysqli_stmt_execute($result);
mysqli_stmt_bind_result($result, $ddd);
$to_time = new DateTime("now", new DateTimeZone("Europe/Athens"));
while(mysqli_stmt_fetch($result)){
// probably want UTC as date times are stored on the db in UTC
// but you may need to experiment with timezones here
$from_date = DateTime::createFromFormat('Y-m-d H:i:s', $ddd, new DateTimeZone("UTC"));
echo round(abs($to_date->getTimestamp() - $from_date->getTimestamp()) / 60,2). " minute";
}
There is no assigment value operation for variable $ids...
I have two dates that are in format Y-m-d
$dateOld = new DateTime("2017-01-10");
$dateNew = new DateTime("2017-01-11");
echo $diff = $dateNew->diff($dateOld)->format("%a");
this is working perfect and giving me exact days left.
But now I have added time and it is in H-M format
Like 23:38 and 17:21 and cannot understand now to get the difference between two dateTime
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
echo $diff = $dateNew->diff($dateOld)->format("%a");
I want to get the difference even if the value if in floating point. Now to work with date concatenated with time?
Use this:
<?php
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-11 17:21");
$diff = $dateNew->diff($dateOld);
$days = $diff->d;
$hours = $diff->h;
$minutes = $diff->i;
$total_difference = $days + ($hours * 60 + $minutes) / 1440;
echo $total_difference;
Or, without the DateInterval:
$dateOld = new DateTime("2017-01-10 23:38");
$dateNew = new DateTime("2017-01-12 17:21");
$difference_in_seconds = $dateNew->getTimestamp() - $dateOld->getTimestamp();
$total_difference_in_days = $difference_in_seconds / 86400;
echo $total_difference_in_days;
Using ->format("%a") will give you the rounded days.
See http://php.net/manual/en/datetime.diff.php.
$dateNew = '2017-01-11 17:21';
$dateOld = '2017-01-10 23:38';
$dateNew = new DateTime($dateNew);
$dateOld = new DateTime($dateOld);
$diff = $dateNew->diff($dateOld);
echo $diff->format("%H:%I");
Source: http://php.net/manual/en/datetime.diff.php
I want to calculate how many weeks there are left from a specific date to another date, in order to get the budget per week. Here's my code:
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo ('3164.49' / $weeksleft);
That code prints 3 167,76 for the last 2 weeks which of course is wrong. But what is wrong with my code?
$date_from = new DateTime('2015-07-28');
$date_to = new DateTime();
$interval = $date_from->diff($date_to);
$daysleft = ($interval->format('%a') + 1);
$weeksleft = number_format($daysleft / 7);
echo (floatval('3164.49') / $weeksleft);
Results
1582.245
You can do it in different way as shown below.
$a = strtotime('2015/07/28');
$b = time();
$diff = abs($a - $b);
echo round($diff/(60*60*24*7)); // to get round figure
try this function,
function datediffInWeeks($date1, $date2)
{
if($date1 > $date2) return datediffInWeeks($date2, $date1);
$first = DateTime::createFromFormat('m/d/Y', $date1);
$second = DateTime::createFromFormat('m/d/Y', $date2);
return floor($first->diff($second)->days/7);
}
var_dump(datediffInWeeks('1/2/2013', '6/4/2013'));// 21
I get 1582.245 .. Check/set your timezone settings.
date_default_timezone_set ($timezone_identifier)
http://php.net/manual/en/timezones.php
i'm trying to add X month to a date taken from my database
$sql_batch = "SELECT * FROM mgm_subscription WHERE status = '1'"
$query_batch = mysql_query($sql_batch);
$row_batch = mysql_fetch_array($query_batch);
$addMonth = 3;
$startDate = $row_batch['start_month'];
$endDate = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endDate = date('m/d/y H:i:s', $endDate );
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startDate."','".$endDate."', '')";
$query_date = mysql_query($sql_date);
NULL was inserted into the end_month.
start_month and end_month is DATE type in the mysql
how do i fix this? tq.
If I understood your question, your $endDate should be
$endDate = date('Y-m-d', strtotime($startDate.' +'.$addMonth.' months'));
So this will equate to:
$endDate = $startDate + 3 months /* in Y-m-d format */
EDIT: Just saw that your column datatype is Date. This would mean that you can't store timestamp in your date. It has to be Y-m-d format only as that is the valid mysql format supported.
You insert $endMonth a value(number of days from form) then you try to replace it ($endMonth) and you call back your replaced variable..
$endMonth = strtotime('+'.$addMonth.' month', $startMonth); // add number of days from form
$endMonth = date('m/d/y H:i:s', $endMonth);
It will return null value.. My suggestion, try to put other variable to prevent duplicate value or missing data
You only mention adding X months. Maybe I misunderstood your question, but if all you care about is the month, I would do the following:
if ($startMonth === 'January') {
$monthNumber = 1;
} else if ($startMonth === 'February') {
$monthNumber = 2;
} //Up to November then finish with {
else {
$monthNumber = 12;//December
}
$newMonthNumber = $monthNumber + $addMonth;
if ($newMonthNumber % 12 == 1) {
$endMonth = 'January';
} else if ($newMonthNumber % 12 == 1) {
$endMonth = 'February';
} //Up to November then finish with {
else {
$endMonth = 'December';
}
$sql_date = "INSERT INTO user_subscription (user_id, start_month, end_month, sub_status) VALUES ('".$usercode2."','".$startMonth."','".$endMonth."', '')";
$query_date = mysql_query($sql_date);
I have a function that creates time intervals between two time marks. The function works but I'm struggling to upgrade from strtotime() and use the DateTime class.
Below is a patch of code I wrote without getting errors
$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');
Next is the entire code untouched. I get DateInterval could not be converted to int erros using the code above. Please kindly advise how to correctly implement the class.
Live example: http://codepad.org/jSFUxAnp
function timemarks()
{
//times are actually retrieved from db
$timestart = strtotime("14:00:00");
$timestop = strtotime("20:00:00");
$time_diff = $timestop - $timestart; //time difference
//if time difference equals negative value, it means that $timestop ends second day
if ($time_diff <= 0)
{
$timestop = strtotime( '+1 day' , strtotime( $row->timestop ) ); //add 1 day and change the timetsamp
$time_diff = $timestop - $timestart;
}
//create interval
$split = 3;
$interval = $time_diff/$split;
//get all timemarks
$half_interval = $interval / 2;
$mid = $timestart + $half_interval;
for ( $i = 1; $i < $split; $i ++) {
//round intervals
$round_mid = round($mid / (15 * 60)) * (15 * 60);
$result .= date('H:i:s', $round_mid) . ", ";
$mid += $interval;
}
$round_mid = round($mid / (15 * 60)) * (15 * 60);
$result .= date('H:i:s', $round_mid);
return $result;
}
outputs 15:00:00, 17:00:00, 19:00:00
Actually you're using DateTime, these are just aliases for creating DateTime instances
The equivalent would look like this:
$timestart = new DateTime("14:00:00");
$timestop = new DateTime("20:00:00");
$date_diff = $timestop->diff($timestart);
$time_diff = $date_diff->format('%H');
So this has to work, I tested it and I got correct results!