calculate years beetwen two dates laravel - mysql

i have mySQL database table field :
description
unit
start_date
end_date
for example :
start_date : 05-07-2019
end_date : 10-08-2021
how I calculate number of years?

Try this with carbon,
use Carbon\Carbon;
$startDate = Carbon::parse('05-07-2019');
$endDate = Carbon::parse('10-08-2021');
$diff = $startDate->diffInYears($endDate);
Hope this helps :)

Try
$datetime1 = new DateTime("05-07-2019");
$datetime2 = new DateTime("10-08-2021");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
Output will be
Difference: 2 years, 1 months, 5 days
Hope this helps :)

Try to use date_diff, in your example its will return 1.
$start_date = date_create("05-07-2019");
$end_date = date_create("10-08-2021");
$diff = date_diff($start_date, $end_date);
echo $diff->y;

Related

Selecting rows that are within 2 hours from current time

I am using PHP with MySQL and would like to select rows that have a booking time within 2 hours from now. How do I compare what is in my database with the NOW() MySQL function?
I have columns pickupDate in the format yyyy-mm-dd and pickupTime in the format HH:mm (24-hour). I have tried creating a query with NOW() which returns the a 12-hour time as HH:mm:ss e.g. 2019-05-24 07:54:06 . I can't figure out how to format this to 19:54, or if I should use a different function instead.
For example, if the current date and time is 24/05/19 19:54:06, I would like to select rows between 19:54 and 21:54 on this date.
My table structure is:
referenceNo VARCHAR(100)
pickupDate DATE
pickupTime VARCHAR(100)
You need to create a DATETIME compatible value out of your pickupDate and pickupTime (which you can do by CONCATing them together), then you can compare that with a time range from NOW() to 2 hours later:
SELECT *
FROM yourtable
WHERE CONCAT(pickupDate, ' ', pickupTime) BETWEEN NOW() AND NOW() + INTERVAL 2 HOUR
Demo on dbfiddle
To add two hours in php
$hoursnow = date('H:i');
$timestamp = strtotime(date('H:i')) + 60*60*2;
$plusTwohours = date('H:i', $timestamp);
And $PlusTwohours using this variable frame the query like below
Sql Query:
$sqlQuery = 'select * from foodorder where pickupDate=DATE(NOW()) AND pickupTime>='.$hoursnow.' and pickupTime<='.$plusTwohours;
$result = mysql_query($sqlQuery);
variable $result will have the values of query
For Second Scenario: Adding hours to end of the day May 24 23:30:00
This should be handle by two different date for same column pickupDate
$d = new DateTime('2011-01-01 23:30:30');
$startDate = $d->format('Y-m-d H:i:s'); // For testing purpose assigned manually
$starttime = date('H:i');
// Here Process start, storing end date by adding two hours
$enddate1 = strtotime($startDate) + 60*60*2;
$enddate = date('Y-m-d', $enddate1); // Extracting date alone
$endtime = date('H:i', $enddate1); // Extracting time alone
Have to compare start and end date for column pickupDate, here is the query
$sqlQuery = "select * from foodorder where pickupDate>=DATE(".$startDate.") AND pickupDate<=DATE(".$enddate.") AND pickupTime>='".$starttime."' AND pickupTime<='".$endtime."'";
$result = mysql_query($sqlQuery);

how can i loop two colum values

I have a table named leaves.
----------
id FromDate ToDate
1 20-01-2019 22-01-2019
2 15-01-2019 22-01-2019
3 13-01-2019 20-01-2019
I want all dates between each column.
Can anyone help?
If you want to do it in your php code then you can do it by finding day count between two days and loop it to get the all dates between that two dates.
<?php
$date1 = "2019-01-13";
$date2 = "2019-01-20";
$date1 = strtotime("2019-01-13");
$date2 = strtotime("2019-01-20");
$datediff = $date2 - $date1;
$days = round($datediff / (60 * 60 * 24));
for($i=1;$i<=$days;$i++){
echo $date1 = date('d-m-Y', strtotime($date1 . ' +1 day'));echo ' <br> ';
}
You can try below using datediff() function
select id, fromdate, todate,datediff(ToDate,fromdate) as days
from tablename

SQL Doctrine year's eve

that's is strange, maybe is my fault. Today I launch my test and 2 of they faults (yesterday dont). This test use a control date of some bookings, and I presume the problem is that today is 31/12. I'll show you the code:
$em = $this->getEntityManager();
$query = $em->createQuery(
'SELECT b
FROM AppBundle:Booking b
WHERE b.bookingDate >= CURRENT_DATE()
AND b.bookingDate <= CURRENT_DATE()+1
ORDER ASC b.bookingDate'
)
return $booking = $query->getResult();
That way is the only way i found to check that the booking have a date at today. Is possible that this fault becouse today is 31/12? Do you have some solution?
sorry for bad english, thanks.
You can calculate the dates by Php:
$today = new DateTime('now');
$tomorrow = new DateTime('tomorrow');
$em = $this->getEntityManager();
$query = $em->createQuery(
'SELECT b
FROM AppBundle:Booking b
WHERE b.bookingDate >= :today
AND b.bookingDate < :tomorrow
ORDER BY b.bookingDate ASC'
);
return $query->setParameters(array(
'today' => $now->format('Y-m-d'),
'tomorrow' => $tomorrow->format('Y-m-d')
))->getResult();
You can avoid var $booking and return result directly.
Also you have missed ; at the end of createQuery and ORDER is ORDER BY.
Also beware with namespaces, maybe you must to use new \DateTime('now');
CURRENT_DATE()+1
returns
20161232
which seems to be pretty wrong.
A way to make it works as you want it to would be this:
DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY);
which returns
2017-01-01

Cannot Get MYSQL DATEADD to Add The Year

This is really puzzling me as DATEADD should work and it isn't and wondered if anyone knew why. Here is my statement:
$r = mysqli_query($con,"SELECT ID, DATEADD(year,1,BEGINDATE) AS NEXTYEAR FROM b_crm_deal");
while($row = mysqli_fetch_array($r))
{
print "".$row['NEXTYEAR']."<br />";
}
This doesn't return anything. If I was to return the BEGINDATE it is:
2015-08-04 00:00:00
I basically want NEXTYEAR to return 2016-08-04 00:00:00. I've tried the different combinations of year, yyyy, yy and nothing is returning.
DATEADD isn't a valid function in MySQL (it's MSSQL), use date_add instead:
DATE_ADD(BEGINDATE, interval 1 year) AS NEXTYEAR
See the manual for more information.
DATEADD looks wrong to me, see https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_adddate
so try:
$r = mysqli_query($con,"SELECT ID, ADDDATE(BEGINDATE, INTERVAL 1 YEAR) AS NEXTYEAR FROM b_crm_deal");
while($row = mysqli_fetch_array($r))
{
print "".$row['NEXTYEAR']."<br />";
}

Perl Date calculations over two months

i have a report which runs weekly on a friday doing some db queries where data is from monday to friday and producing a table with the results. I am having a problem when the report runs on a friday where the monday is last month. So for example last friday. Friday was the first of august, and the monday was the 28th of july. The below is the date and time portion of my script.
my $date = `date +%Y%m%d`;
chomp($date);
my $time = `date +%H%M%S`;
chomp($time);
my $day = `date +%A`;
chomp($day);
my $time = `date +%H%M%S`;
chomp($time);
my $dispTime = `date +%H:%M`;
chomp($dispTime);
# Set the Dates
my $end = $date;
my $start = $end;
# Check the day and define start and end dates.
if ($day eq "Friday") {
$start = $end - 5;
my #mytime=localtime;
my ($s, $min, $h, $d, $m, $y) = (0, 0, 0, $mytime[3], $mytime[4], $mytime[5]);
my $todayminus5 = strftime "%Y%m%d", $s, $min, $h, $d - 5, $m, $y;
$start = $todayminus5;
In my report logs it prints the date that was calculated and it printed this
Start Date = 2014080,
End Date = 20140801
Does anybody know why this doesnt seem to be able to calculate the date if its over two months?
You should use Time::Piece in conjunction with its sister module Time::Seconds. If you have a reasonably recent version of Perl then it should already be installed as it has been a core module since version 10 of Perl 5.
By the way, you need to subtract four days to get from Friday to the previous Monday!
use strict;
use warnings;
use Time::Piece;
use Time::Seconds 'ONE_DAY';
my $now = localtime;
if ($now->wdayname eq 'Fri') {
my $monday = ($now - ONE_DAY * 4)->strftime('%Y%m%d');
# etc.
}
I would rework the approach you're taking - you're doing multiple invocations of date which is probably a warning sign in the first place. You've got a whole lot of edge cases - subtracting '5' from your days will get you a negative number if it's early in the month - which will break things - but you'll have similar problems when the year changes.
I won't contradict the previous post, but I'd instead suggest you simplify:
my $ONE_DAY_s = 60 * 60 * 24;
my $now = time();
my $then = $now - 4*$ONE_DAY_s;
my ( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($now);
$year += 1900;
print "Now: $year $mon $mday\n";
( $sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($then);
$year += 1900;
print "Then: $year $mon $mday\n";
(transcribed, rather than pasted so beware typos).
You can use $wday to figure out if it's a friday.
Modules exist to do this as well though - I would be very wary of using repeated invocations of an external command, and then trying to mangle the results.
You can use the Datetime module to get the start date and end date
Example:
use strict;
use warnings;
use DateTime;
my $today_date = DateTime->today(); # Current date (Friday)
my $old_date = $today_date->clone()->subtract(days => 4); # First DoW (Monday)
print $today_date, "\n";
print $old_date, "\n";
Outputs:
2014-08-04T00:00:00
2014-07-31T00:00:00