I have problem getting the year
I have here in my database year of 11/11/2016 - 11/13/2015 - 11/13/2014
the problem is I want to get that year just deducting current year
so if the current year is 2017 I want to get 2016,2015,2014 , and the next year
2018 the year will get is 2017,2016,2015
$selectmemberpaid = mysql_query("SELECT
memberid,StartDate,EndDate,tblpayments.activityname,amount_paid FROM
tblattend_activity LEFT JOIN tblpayments ON tblattend_activity.memberid =
.profile_id WHERE memberid='201400001'");
That is my query..
and this is my while loop
while ($rows = mysql_fetch_assoc($selectmemberpaid)) {
# code...
$dateTimestamp = strtotime($rows['StartDate']);
$year = date("Y", $dateTimestamp);
}
You can get the year from a date string by doing something like this:
$dateTimestamp = strtotime('2015-12-12');
$year = date("Y", $dateTimestamp);
echo $year;
Once you get it you can add or subtract to get the previous/next year (after converting the value into an integer).
I'm not sure I understand what you're asking but:
Query!
$rest = substr(date('d-m-Y'), 6);
$rep = $idz->query("SELECT * FROM stack1 where SUBSTR(date_depart, 6) < $rest
order by SUBSTR(date_depart,6) desc limit 3");
while ($row = $rep->fetch())
{
echo $row['date_depart'];
//echo "<br>";
}
$rep->closeCursor();
Result
Related
I have a user in a database with a creation_date. This user can run a job in my app UI, but he is limited by a number of job to run in one year.
This user has been created in 2014. I would like to do something like :
function runJob($user){
$nbRemainingJob = findReminingJobs($user);
if ($nbRemainingJob > 0){
runJob($user);
}
else {
die("no more credits";)
}
}
findReminingJobs($user){
$dateRangeStart = ?; //start date to use
$endRangeStart = ?; //end date to use
$sql = "SELECT count(*) FROM jobs WHERE user_id=?";
$sql .= "AND job_created_at BETWEEN ($dateRangeStart AND $endRangeStart)";
$res = $pdo->execute($sql, [$user->id]);
$done = $res->fetchOne();
return ($user->max_jobs - $done);
}
Every user's creation birthday, the $user->max_jobs is reset.
The question is how to find starting/ending date ? in other words, I would like to get a range of date starting from the user's creation date.
For example, if the user was created on 2014-04-12, my start_date should be 2018-04-12 and my end_date = 2019-04-11.
Any idea ?
First get the user register date from db and split it into Year, Month and Day like
$register= explode('-', $userCridate);
$month = $register[0];
$day = $register[1];
$year = $register[2];
Then get the current year like
$year = date("Y");
$dateRangeStart = $year."-".$month."-".$day; //start date to use
Now, check if this date is greater then today date, then use last year as starting date
$previousyear = $year -1;
$dateRangeStart = $previousyear ."-".$month."-".$day; //start date to use
$endRangeStart = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dateRangeStart))
. " + 365 day"));
It is a idea, check if it work for you.
function getRange($registrationDate) {
$range = array();
// Split registration date components
list($registrationYear, $registrationMonth, $registrationDay) = explode('-', $registrationDate);
// Define range start year
$currentYear = date('Y');
$startYear = $registrationYear < $currentYear ? $currentYear : $registrationYear;
// Define range boudaries
$range['start'] = "$startYear-$registrationMonth-$registrationDay";
$range['end'] = date("Y-m-d", strtotime($range['start'] . ' + 364 day'));
return $range;
}
And for your example:
print_r(getRange('2014-04-12'));
Array
(
[start] => 2018-04-12
[end] => 2019-04-11
)
print_r(getRange('2014-09-13'));
Array
(
[start] => 2018-09-13
[end] => 2019-09-12
)
$created='2025-04-12';
$date=explode('-',$created);
if($date[0]<date("Y")){
$newDate=date('Y').'-'.$date[1].'-'.$date[2];
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
else{
$newDate=$created;
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
echo 'starting date is: '.$newDate;
echo '</br>';
echo 'ending date is: '.$dateEnding;
This code will get the date you have and match it with the current year. If the year of the date you provided is equal or above the current year the start date will be your date and end date will be current date +1 year. Otherwise if the year is below our current year (2014) it will replace it with the current year and add 1 year for the end date. Some example outputs:
For input
$created='2014-04-12';
The output is :
starting date is: 2018-04-12
ending date is: 2019-04-12
But for input
$created='2025-04-12';
The outpus is :
starting date is: 2025-04-12
ending date is: 2026-04-12
The solution that match my need :
$now = new DateTime();
$created_user = date_create($created);
$diff = $now->diff($created_user)->format('%R%a');
$diff = abs(intval($diff));
$year = intval($diff / 365);
if ($year == 0){
$startDate=$created_user->format("Y-m-d");
}else{
$startDate=$created_user->add(new DateInterval("P".$year."Y"))->format("Y-m-d");
}
The problem was to define the starting date that is comprised in the one year range max from the current date and starting from the user's creation date.
So if the user's creation_date is older than one year, than I do +1 year, if not, take this date. the starting date must not be greater than the current date_time
thanks to all for your help
I want to get the sales per year I have this code (please see below), that gets the column name and format it into (please see below). I have start date and end date I want to get the all the months between the two years. For example start date = 01/01/2017 and end date = 01/01/2018 I want go get the months between them and format it into SUM(JAN_2017) AS JAN_2017, etc and at the same time get the sum of all the months for the year 2017 and 2018.
SCREENSHOT OF MY TABLE
THIS IS MY COLUMN NAME SAMPLE (PLEASE REFER TO THE SCREENSHOT):
JAN_2017, FEB_2017 UPTO DEC_2017
SAMPLE OUTPUT OF MY CODE:
SUM(JAN_2017) AS JAN_2017, etc.
CODE:
$start = new DateTime($_POST["start"]);
$end = new DateTime($_POST["end"]);
$smonth = (int)$start->format('Y')*12+(int)$start->format('n');
$emonth = (int)$end->format('Y')*12+(int)$end->format('n');
$firstmonth = min($smonth, $emonth);
$lastmonth = max($smonth, $emonth);
$months = array();
for ($i = $firstmonth; $i <= $lastmonth; $i++) {
$thism = new DateTime(sprintf('%04d-%02d-01', intdiv($i, 12), $i % 12));
$months[] = strtoupper($thism->format('M_Y'));
}
$m_total = implode(',', preg_replace('/^(.*)$/', 'SUM($1) AS $1', $months));
$m_average = implode(',', preg_replace('/^(.*)$/', 'AVG($1) AS $1', $months)
);
This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 5 years ago.
I have a table in MySQL with a date field (called NDate) which contains standard date values ("2017-04-17","2017-04-18", etc.).
Through PHP webpage, I am trying to take the system date (say today is 2017-04-17), and then pull all rows from the above table where NDate="2017-04-17". No issues till here.
I have a requirement to increment the day (starting today and going on for next 10 days - i.e. 2017-04-17 to 2017-04-26), and for each day report entries under a different heading like "Entries for 2017-04-17" which will list all rows having NDate 2017-04-17, "Entries for 2017-04-18" which will list all rows having NDate 2017-04-18.
I was trying to use a for loop with PHP date_modify function to increment the days one by one, but it is not showing any results.
Here are the selected pieces of code:
date_default_timezone_set('US/Eastern');
$datev = date("Y-m-d");
for ($x = 0; $x <= 10; $x++)
{
$datev=date_modify($date,"+$x days");
echo "before date format<br>"; // echo statement 1
echo "date is: $datev <br>"; // echo statement 2
$sql = "SELECT * FROM tablename where Ndate='$datev'";
echo "before result<br>"; // echo statement 3
...
...
...
}
Output on webpage shows only statement 1. But echo stats 2 and 3 are not printed.
You can increment days using strtotime function as a parameter to date function.
For 10 days, you can use for loop, to build an array of days. Then iterate over it, to execute queries you need.
$today = date('Y-m-d');
$dates=array($today);
for($i=1;$i<10;$i++) {
$NewDate=date('Y-m-d', strtotime("+".$i." days"));
$dates[]=$NewDate;
}
foreach($dates as $dt) {
// sql stuff here
echo "date is: $dt <br>";
$sql = "SELECT * FROM tablename where Ndate='$dt'";
echo "before result<br>";
// .....
}
This code should work for your case. If any problems, just let me know.
Try this:
$start = strtotime(date('Y-m-d'));
$end = strtotime(date('Y-m-d', strtotime('+10 days')));
while($start <= $end)
{
$date = date('Y-m-d', $start);
//use $date to do stuff
//SELECT * FROM tablename where Ndate='$date'
$start = strtotime("+1 day", $start);
}
i need to list total post article archive by years and months like this :
Output(my need):
2014
January(31)
February(28)
March(0)
April(130)
May(450)
June(0)
July(0)
August(0)
September(0)
October(520)
November(20)
December(31)
PHP:
$sql = "SELECT title, YEAR(FROM_UNIXTIME(timestamp)) AS YEAR,
MONTHNAME(FROM_UNIXTIME(timestamp)) AS MONTH,
COUNT(*) AS TOTAL
FROM article GROUP BY YEAR, MONTH ORDER BY YEAR DESC, MONTH ";
$newsdata = DB->fetch($sql);
$currentYear = null;
foreach($newsdata AS $news){
if ($currentYear != $news['YEAR']){
echo '<ul>'.$news['YEAR'].'</ul>';
$currentYear = $news['YEAR'];
}
echo '<li>'.$news['MONTH'].' '.$news['TOTAL'].'</li>';
}
My code worked but print only month if posted article in this month.
Ouput:
2014
January(31)
February(28)
April(130)
May(450)
October(520)
November(20)
December(31)
I need to list all month and print total article for each month. if month not posted article print (0) for this month.
how do can i fix my problem? my code/way is true?!
Your database query won't return a row for a month that has no articles. It doesn't know anything about months. So you need to handle this in code by having an array of all months and looping through that. The alternative would be to alter your schema, have another table with all 12 months, and join on that. But I think the following is easier for you:
$months = array( "January", "February", ... );
Then you can do the following in your output instead:
// Index article counts by month and year for easy lookup
$indexedNewsData = array();
foreach ($newsdata as $news) {
$indexedNewsData[$news['YEAR']][$news['MONTH']] = $news['TOTAL'];
}
// Then print output
foreach($newsdata AS $news){
if ($currentYear != $news['YEAR']){
echo '<ul>'.$news['YEAR'].'</ul>';
$currentYear = $news['YEAR'];
} else {
// Continue here otherwise we will print each year's data 12x
continue;
}
foreach ($months as $month) {
$total = intval($indexedNewsData[$news['YEAR']][$month]);
echo '<li>'.$month.' '.$total.'</li>';
}
}
How I can convert INT to date in php and than find this date in mysql table ?
Lets say I want to convert
$month = (int)$_GET['month'];
$month = 42014 ;//This means 04th month in 2014 year
$month = 04-2014; // I want this
And than find that in mysql table
$query=mysql_query("SELECT id FROM matches WHERE date=$month");// This need to select
// all data that is
// created in 04th month
// of 2014 year .
echo "Thanks :)";
Don't pass $month parameter like you do.
Send and pass both $month and $year and handle them after:
$month = (int)$_GET['month'];
$year = (int)$_GET['year'];
if($month < 10) { // add this check for months lesser then october (they containt 1 digit, which is wrong for t-sql)
$month = "0".$month;
}
$query=mysql_query("SELECT id FROM matches WHERE DATE_FORMAT(datefield, '%m-%Y') = '$month-$year'");
source
If you can't send both month and year in different variables, do this, like M Khalid Junaid suggested:
$query=mysql_query("SELECT id FROM matches WHERE DATE_FORMAT(datefield,'%m%Y')='$month'");
Try as below using DateTime::createFromFormat
$month = $_GET['month'];
$date = DateTime::createFromFormat('mY',$month);
echo $date->format('m-Y');
Try this
$input=42014;
$year = strlen(substr($input,-4));
$month = substr(0,(strlen($input)-strlen($year)));
$final = $month."-".$year