Currently I'm stuck with some MySQL queries.
I have a table like this:
ID|USERID|USERNAME|STARTTIME|ENDTIME|COMMITTYPE
The users click buttons in a frontend -> Start <- and -> Stop <-.
This creates a db entry with their respective duties, starttime and endtime. So, each click on start creates a new row/entry in the db and will get finished by the click on the stop button.
My problem, is there a chance to count the overall time between the start time and the end time per user and commit type?
This probably work
SELECT USERID, COMMITTYPE, MIN(STARTTIME), MAX(ENDTIME),
SUM(TIME_TO_SEC(TIME_DIFF(ENDTIME - STARTTIME))/3600) hours FROM tablename
GROUP BY USERID, COMMITTYPE
Do you refer to something like this?
SELECT COMMITTYPE, USER, (ENDTIME - STARTTIME) AS ELLAPSED_TIME
FROM YOUR_TABLE GROUP BY COMMITTYPE, USERID;
SELECT DATEDIFF('new_date', 'old_date');
// eg
SELECT DATEDIFF('2006-04-01','2006-04-01');
IG GETTING USE LINUX
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
///
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";
OUTPUT
6 years
18 years, 11 months, 30 days, 23 hours, 59 minutes, 59 seconds 2
months 6 years, 2 months, 10 days 4 years, 11 months, 30 days, 8
hours, 21 minutes, 49 seconds
Related
Ok simple enough problem I hope but I'm probably overthinking the solution.
I have a mysql table with a timestamp formatted datetime. This is how it appears in the database (2016-10-08 03:56:26).
I created a function that is suppose to show the difference between the timestamp and the current time (UTC), which is constantly increasing. Please review my code. Currently it works... somewhat. The issue is when a time stamp is created at Noon (CST). The output will say 11hrs have ellapsed which is not true. All help is appreciated.
<?php
// Set timezone
date_default_timezone_set("America/Chicago");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(" ", $times);
}
?>
Use the PHP object oriented date commands to convert a time from one time zone to another before you do your comparison.
http://php.net/manual/en/datetime.settimezone.php
Another approach in PHP is to use Carbon. It has handy methods as well as comparison methods. It's used in Laravel and has a stable position on the market.
Check this: http://carbon.nesbot.com/docs/#api-difference and maybe you'll find out that there's no point of reinventing the wheel.
This worked the best for me. I'll add the link for the question that helped me out with this. LINK HERE
<?php
$dt = new DateTime($row['ticketopen']);
$now = new DateTime('now');
$interval = $dt->diff($now);
?>
I'm trying to calculate the number of months and weeks since a particular date instead of from the beginning of the year.
It shouldn't follow calendar months but should instead count a month as every 4 weeks, and begin from a specified date. I need to be able to display the number of months, and also what week it is (1, 2, 3 or 4).
I want to put in a start date, and have it then count what month and week is it from that start date e.g if the start date is set to Mon 1st August it should show Month 1, Week 1 and so on.
My code is below. I tested it with some different start dates. Here's a list of what the code below generates and what it should display
Jun-20: Should be Week 2 - Shows as Week 0
Jun-27: Should be Week 1 - Shows as Week 3
Jul-04: Should be Week 4 - Shows as Week 2
Jul-11: Should be Week 3 - Shows as Week 1
Jul-18: Should be Week 2 - Shows as Week 0
$monthNumber = 5;
$monthStartDate = '2016-06-13';
$currentStartWeekDate = date('l') != 'Monday' ? date("Y-m-d", strtotime("last monday")) : date("Y-m-d"); // get the current week's Monday's date
$weekDateCounter = $monthStartDate;
$currentWeekNumber = 0;
while ($weekDateCounter != $currentStartWeekDate){
$currentWeekNumber += 1;
$weekDateCounter = date("Y-m-d", strtotime($weekDateCounter . "+7 days"));
//
if ($currentWeekNumber == 4){
$currentWeekNumber = 0; // reset week number
$monthNumber += 1; // increment month number
}
}
I am really at a loss with this and could use any help!
Your approach seems overly complicated:
function weekCounter($startDate,$endDate=null){
//use today as endDate if no date was supplied
$endDate = $endDate? : date('Y-m-d');
//calculate # of full weeks between dates
$secsPerWeek = 60 * 60 * 24 * 7;
$fullWeeks =
floor((strtotime($endDate) - strtotime($startDate))/$secsPerWeek);
$fullMonths = floor($fullWeeks/4);
$weeksRemainder = $fullWeeks % 4; // weeks that don't fit in a month
//increment from 0-base to 1-base, so first week is Week 1. Same with months
$fullMonths++; $weeksRemainder++;
//return months and weeks in an array
return [$fullMonths,$weeksRemainder];
}
You can call the function this way, and capture months and weeks:
//list() will assign the array members from weekCounter to the vars in list
list($months,$weeks) = weekCounter('2016-06-07'); //no end date, so today is used
//now $months and $weeks can be used as you wish
echo "Month: $months, Week: $weeks"; //outputs Month: 2, Week: 2
Live demo
The DateTime classes could make this much simpler for you. Documentation for them is here: http://php.net/manual/en/book.datetime.php
Try this out:
$date1 = new DateTime('2016-04-01');
$date2 = new DateTime('2016-07-24');
$diff = $date1->diff($date2);
$daysInbetween = $diff->days;
$weeksInbetween = floor($diff->days / 7);
$monthsInbetween = floor($weeksInbetween / 4);
print "Days inbetween = $daysInbetween" . PHP_EOL;
print "Weeks inbetween = $weeksInbetween" . PHP_EOL;
print "Months inbetween = $monthsInbetween" . PHP_EOL;
print "Total difference = $monthsInbetween months and "
. ($weeksInbetween - ($monthsInbetween * 4)) . " weeks" . PHP_EOL;
<?php
/**
* AUTHOR : VEDAVITH RAVULA
* DATE : 13122019
*/
function get_weeks($startDate = NULL,$endDate = NULL)
{
if(is_null($startDate) && is_null($endDate))
{
$startDate = date('Y-m-01');
$endDate = date('Y-m-t');
}
$date1 = new DateTime($startDate);
$date2 = new DateTime($endDate);
$interval = $date1->diff($date2);
$weeks = floor(($interval->days) / 7);
if(($date1->format("N") > 1) && ($date1->format("D") != "Sun"))
{
$diffrence = "-".( $date1->format("N"))." Days";
$date1 = $date1->modify($diffrence);
}
for($i = 0; $i <= $weeks; $i++)
{
if($i == 0)
{
$start_date = $date1->format('Y-m-d');
$date1->add(new DateInterval('P6D'));
}
else
{
$date1->add(new DateInterval('P6D'));
}
echo $start_date." - ".$date1->format('Y-m-d')."\n";
$date1->add(new DateInterval('P1D'));
$start_date = $date1->format('Y-m-d');
}
}
//function call
get_weeks("2021-11-01", "2021-11-14");
I have 2 time strings for example OPEN = 11:00 and closed is 02:45
now the 02:00 is the next day so i to the following:
//open = string 11:00
//closed= string 02:45
$open = \DateTime::createFromFormat('H:i', $open);
$closed = \DateTime::createFromFormat('H:i', $closed);
if ($open > $closed) $closed->modify('+1 day');
now i have 2 proper datetime formats. Now i want to set a time interval of 30 minutes from the open time to the close time. How can i do this? i have read i can add like this
->add(new DateInterval('PT30M') b
ut it will add till the end of the day.. but in this case its open till the next day, so i want it to populate till 2:45AM
how can i do this?
You where on the right track. Here is how to do it using DateInterval('PT30M').
$strOpen = '11:00';
$strClose = '02:45';
$open = DateTime::createFromFormat('H:i', $strOpen);
$closed = DateTime::createFromFormat('H:i', $strClose);
if ($open > $closed) $closed->modify('+1 day');
// I display not only the time, but the day as well to show that it is
// incrementing to the next day.
echo 'open: ' . $open->format('D H:i') . "<br />\n";
while ($open < $closed) {
$open->add(new DateInterval('PT30M'));
// because incrementing on the half hour and our finish is on the 15 min,
// the last is $open < $close in the while statement will be true but
// this loop will generate a time after $closed so we do another check
// now to eliminate that issue
if ($open < $closed) {
echo '+30min: ' . $open->format('D H:i') . "<br />\n";
}
}
echo 'closed: ' . $closed->format('D H:i') . "<br />\n";
I have a form here (https://nursinggroup.com/pharmacist-profile/) where users will put in a date in the form of "mm / yy" for bot a "from" input box and a "to" input box. After the user goes through and adds in all their dates, they submit the form and a PDF is created using Gravity Forms PDF Extended (mPDF). What I need to happen is that during the creation of the PDF I need it to calculate the values for each item and spit out the total amount of years onto the PDF for each one.
So for example, if I enter in the following entries on the online form:
Ambulatory Care "From: 02 / 88" "To: 02 / 98"
Home Healthcare "From: 07 / 02" "To: 07 / 05"
Oncology "From: 09 / 06" "To: 05 / 12"
On the PDF it would spit out the following:
Ambulatory Care 10
Home Healthcare 3
Oncology 5.8
I have read through and tried many different code samples out there, but I am just not skilled enough with this type of PHP to make this work. A few other things to keep in mind. This is on a WordPress site, using Gravity Forms for the forms, and Gravity Forms PDF Extended to create the PDF's from those forms. Another thing to note, is that the entry of the year must remain in yy format versus yyyy The user does not fill in a day as well, only mm / yy
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Create temp time from time1 and interval
$ttime = strtotime('+1 ' . $interval, $time1);
// Set initial values
$add = 1;
$looped = 0;
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
// Create new temp time from time1 and interval
$add++;
$ttime = strtotime("+" . $add . " " . $interval, $time1);
$looped++;
}
$time1 = strtotime("+" . $looped . " " . $interval, $time1);
$diffs[$interval] = $looped;
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
What I would do is create separate fields for the calculated numbers. This way you can output them directly in the PDF via the entry ID rather than having to run any custom during the PDF creation process.
To calculate the number of years, I would recommend using something like this:
http://gravitywiz.com/calculate-number-of-days-between-two-dates/
It will calculate the number of days; however, it could be easily modified to calculate the number of years by changing this line:
dayCount = diff / ( 60 * 60 * 24 * 1000 );
...to this:
dayCount = diff / ( 60 * 60 * 24 * 360 * 1000 );
You could rename the variable as well but you'll need to replace it everywhere it is referenced in the current scope.
I have a mySQL database.
I need to count the number of days between two dates.
My client is going to fill an input hm_date with January 1, 1979 via php form to create a new record.
I need a field total_days to calculate the total number of days from hm_date to the present day. I need this field to always update itself with each passing day.
How do I make hm_date to appear with total days and be always updated?
I asume this can be achieved server-side?
Should I use strototime() ?
You'll want to use MySQL's DATEDIFF()
DATEDIFF() returns expr1 – expr2 expressed as a value in days from one
date to the other. expr1 and expr2 are date or date-and-time
expressions. Only the date parts of the values are used in the
calculation.
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30');
-> 1
mysql> SELECT DATEDIFF('2010-11-30 23:59:59','2010-12-31');
-> -31
Based on your question I think you would want DATE_DIFF(hm_date, CURRENT_DATE). Just make sure hm_date is in YYYY-MM-DD format.
With PHP:
$daydiff = floor( ( strtotime( $endDate ) - strtotime( $startDate ) ) / 86400 );
$startDate and $endDate can be any valid date format explained here:
http://www.php.net/manual/en/datetime.formats.date.php
Its pretty easy but long.. Please follow following codes
<?php
// Set timezone
date_default_timezone_set("UTC");
// Time format is UNIX timestamp or
// PHP strtotime compatible strings
function dateDiff($time1, $time2, $precision = 6) {
// If not numeric then convert texts to unix timestamps
if (!is_int($time1)) {
$time1 = strtotime($time1);
}
if (!is_int($time2)) {
$time2 = strtotime($time2);
}
// If time1 is bigger than time2
// Then swap time1 and time2
if ($time1 > $time2) {
$ttime = $time1;
$time1 = $time2;
$time2 = $ttime;
}
// Set up intervals and diffs arrays
$intervals = array('year','month','day','hour','minute','second');
$diffs = array();
// Loop thru all intervals
foreach ($intervals as $interval) {
// Set default diff to 0
$diffs[$interval] = 0;
// Create temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
// Loop until temp time is smaller than time2
while ($time2 >= $ttime) {
$time1 = $ttime;
$diffs[$interval]++;
// Create new temp time from time1 and interval
$ttime = strtotime("+1 " . $interval, $time1);
}
}
$count = 0;
$times = array();
// Loop thru all diffs
foreach ($diffs as $interval => $value) {
// Break if we have needed precission
if ($count >= $precision) {
break;
}
// Add value and interval
// if value is bigger than 0
if ($value > 0) {
// Add s if value is not 1
if ($value != 1) {
$interval .= "s";
}
// Add value and interval to times array
$times[] = $value . " " . $interval;
$count++;
}
}
// Return string with times
return implode(", ", $times);
}
?>
Now try this and see how it shows the difference...
echo dateDiff("2010-01-26", "2004-01-26") . "\n";
echo dateDiff("2006-04-12 12:30:00", "1987-04-12 12:30:01") . "\n";
echo dateDiff("now", "now +2 months") . "\n";
echo dateDiff("now", "now -6 year -2 months -10 days") . "\n";
echo dateDiff("2009-01-26", "2004-01-26 15:38:11") . "\n";