Increment through date on week basis - php

I am building a php application using pgsql as its back end.
I would like to increment the date by some amount of date shich should be loaded from my database which have given value as available=1,3,5(implying monday,wednesday,friday of a week).I would like to increment these available values to current date. I am using N format in date() function to represent the values of days in a week as 1 to 7 which is stored in available field in the database
If current date =22-07-2013 which is monday,then i have to increment this to wednesday(available=3) and then to friday(available=5) And then to monday of the next week.
And so on..
but i cant do that..
i am in need of such a code where the value of available may change according to the tuples in that tuple.So i would like to increment the current date based on the value of available.
So please help me to achieve it.
The code I used is attached herewith.Please have a look at it.
<?php
$sq = "SELECT * FROM $db->db_schema.dept where active='Y' and dept_id=$dept_id";
$result = $db->query($sq);
$ftime=$result[0]['f_time'];
$ttime=$result[0]['t_time'];
$a=date('Y-m-d').$ftime;
$b=date('Y-m-d').$ttime;
$to_time = strtotime("$b");
$from_time = strtotime("$a");
$minutes= round(abs($to_time - $from_time) / 60,2). " minute";
$days=array();
$days= explode("," , $result[0]['available']);
$result[0]['available'];
$intl=$result[0]['slot_interval'];
$slots=$minutes/$intl;
$dt1 =date("m/d/Y $ftime ");
$s_mnts=explode(":",$ftime);
$m= date('N');
-- $dt=array();
$a=$dt1;
$l=0;
for($n=1;$n<=3;$n++)
{
for($k=$m;$k<=7;$k++)
{ $l=$l+1;
if(in_array($m,$days))
{
echo "dasdsa";
echo date("Y-m-d H:i:s", strtotime("$a +$l days"));
echo"<br>";
}
$m=$m+1;
if($m==7){$m=1;}
}
}
?>
where
dept_id -> primary key of the table dept
$db->query($sq); -> query is used to fetch the given values and is defined in another file named database.php in the program folder.
f_time and t_time -> fields in the table dept which describes the from_time and to_time.f_time is the time from which we have to start increment and t_time is the time to end this increment.
Please inform me whether there is any improvement in the code I have given. .

What you could do is something like this:
You say how many days you want to increment. And give an array of availables.
<?php
$inicialDate = time(); //Timestamp of the date that you are based on
$tmpDate = $inicialDate; //Copy values for tmp var
$increment = 5; //Increment five days
$available = [1,3,5]; //Days available
/*Ok, now the logic*/
while($increment > 0){
$tmpDate = strtotime("+1 day", $tmpDate); //Increase tmpdate by one day
if(in_array(date("N",$tmpDate), $available){ //If this day is one of the availables
$increment--;
}
}
$finalDate = date("m/d/Y",$tmpDate);
?>
This logic should work, although I don't know how to reproduce it via a SQL Procedure.

From what I can tell, you are after something like
UPDATE sometable
SET some_date_column = some_date_column + ('1 day'::INTERVAL * some_integer_value);

Related

Extract only the number of the day of the date and compare it with the current one

I need to extract only the day number of a user's registration date.
And extract only the day number of the current date.
Simply in an if loop, say if the day number the user registered is equal to the day number of the current date, do this, or do that.
Code:
$manager = "Manager";
$managerPRO = "ManagerPRO";
$q = $connessione->prepare("
SELECT * FROM collaboratori
WHERE cat_professionisti = ?
OR cat_professionisti = ?
");
$q->bind_param('ss', $manager,$managerPRO);
$q->execute();
$r = $q->get_result();
while($rr = mysqli_fetch_assoc($r)){
/*REGISTRATION DATE*/
$registrazione = $rr['data_registrazione'];
$timestamp = strtotime($registrazione);
echo date("d", $timestamp) .'=' ;
/*CURRENT DATE*/
$data_corrente = date('Y-m-d');
$timestamp_uno = strtotime($data_corrente);
echo date("d", $timestamp_uno);
/*CONTROL*/
if ($timestamp == $timestamp_uno){
echo "yes".'<br>';
}else{
echo "no".'<br>';
}
}
Result:
18=18no
17=18no
16=18no
16=18no
Why in the first case if 18 = 18 gives me false?
However, if I change the date of the user's registration and therefore the first 18, from 2020/11/18 to 2020/12/18, then the current month gives me yes!
I need that regardless of the month, just by checking the day if it is the same, tell me yes, where am I wrong?
You are comparing timestamps, which are measured in seconds. What you are doing is effectively comparing two different points in time, not the days of the month.
You really should be using DateTime. If you want to compare only the day part then you can do something like this.
$dt1 = new DateTime($registrazione);
$dt2 = new DateTime(); // defaults to now
if($dt1->format('d') === $dt2->format('d')) {
echo "Yes, it's the same day of the month";
} else {
echo 'no!';
}

Increment days in PHP MySQL date [duplicate]

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);
}

PHP Incrementing date with day name

I am currently attempting to get a list of dates from a current date using the following format so that I can process it and stick it in my database
Saturday/02-05-2015
So far, i've managed to get the system to output the date correctly, but can not get it to increment in single day values.
My current code to attempt to increment this is the following
$tempStartDateN = ("$splode[0]/$splode[1]/$splode[2]/$splode[3]");
echo $tempStartDateN;
$tempStartDateN = date('l/d/m/Y', strtotime($tempStartDateN . ' + 1 day'));
echo $tempStartDateN;
I am currently using explode to process the data after the increment, which works fine, but can not get the date itself to increment as long as the day name is included.
Currently, the time is got using this code, which is processed afterwords using explode
$OldDateArray = date("Y/m/d/l");
So to keep a long question short, what is the best way to increment a date that requires the day name, day, month then year?
EDIT:
Heres my current code, managed to get this far thanks to SamV
$date = date("l/d/m/Y");
echo $date;
echo ('</br>');
list($weekdayName, $dateString) = explode("/", $date, 2);
$dateObj = new \DateTime($dateString);
for($i=0; $i<=5; $i++){
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
echo ('</br>');
}
What this does however is:
Friday/01/05/2015
Tuesday/06/01/2015
Wednesday/07/01/2015
Thursday/08/01/2015
Friday/09/01/2015
Saturday/10/01/2015
Sunday/11/01/2015
this means that date and month are swapping around, what is causing this?
You don't need to parse the week day name to add days onto a date.
$date = "Saturday/02-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "02-05-2015"
$dateObj = new \DateTime($dateString);
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y"); // Sunday/03/05/2015
I used the DateTime class, here is the documentation.
I wrote out what you are trying to do yourself, not sure what is causing your issue. This code works though.
$date = "Friday/01-05-2015";
list($weekdayName, $dateString) = explode("/", $date, 2); // Parse "01-05-2015"
$dateObj = new \DateTime($dateString);
for($i = 0; $i < 5; $i++) {
$dateObj->add(new \DateInterval("P1D")); // P1D stands for "Period 1 Day"
echo $dateObj->format("l/d/m/Y") . '<br>';
}
Outputs:
Saturday/02/05/2015
Sunday/03/05/2015
Monday/04/05/2015
Tuesday/05/05/2015
Wednesday/06/05/2015
If strtotime is able to parse a date it returns the timestamp. Why not add to it the number of seconds in a day? Smth. like $timestamp += 24 * 3600;
P.S. As far as I can understand, strtotime may accept timestamp as second argument (http://us2.php.net/manual/en/function.strtotime.php) smth. like $timestamp = strtotime('+1 day', $timestamp);

Reference number which automatically resets every month

I am generating reference no REF-082013-001 (REF-mmyyyy-001) and incrementing the last part for every entry. REF-082013-001 for first record and REF-082013-002 for second and so on.
My Question is How can i reset the last number by php for every new month. Let say September 2013 I want it to be REF-09-2013-001 and auto increment it till the end of September and then in November reset it again.
Is there a ways to do this in php. Your help is much appreciated. Thank you
Update
Currently 'REF-'.date('m-Y').$maxnumberfromdb in single column called reference_no and Now thinking to store the mm-yyyy ref1 and last number in ref2 separately and start ref2 every first day of the month.
You can probably go with a single table, with an AUTO_INCREMENT field to handle the last part of the reference number, and a date/time field to track when it was last reset.
CREATE TABLE track_reference
ref_number INT(11) AUTO_INCREMENT,
last_reset DATETIME;
Then you write a function in PHP to get a new reference number, which (pseudo-code):
if (MONTH(time()) > MONTH(last_reset)) {
reset ref_number to 0 (use ALTER TABLE);
}
select (ref_number) into $variable;
return 'REF_<month><year>_$variable;
}
It's rough, but you get the idea. I'd also have YEAR appear before MONTH for making sorting by reference number easier later.
This is my code for reset counter and update last_reset, this is effective for me
<pre>
$date2 = new DateTime("now", new DateTimeZone('America/New_York') );
$month_end = strtotime('last day of this month', time());
$count = $data['sim_tarif_count'];
$date3=$date2->format('Y-m-d');
foreach ( $count as $r2 ){
$counts[] = $r2['count'];
$last_reset[] = $r2['last_reset'];}
$paddedNum = sprintf("%04d", $counts[0]);
$reg_id = 'SEQ'.$date2->format('Ymd').$paddedNum;
echo " ";
echo date('j', $month_end);
$counter = $counts[0]+1;
//for reset
if($date2->format('Y-m') > $last_reset[0])
{
$counter = 0;
$counting_update=$this->docs_model->update_time_counter($counter,$date3);
echo $counter = 0;
} else
{
$counting_update=$this->docs_model->update_time_count($counter);
}
</pre>

TV guide written in PHP - problems with datetime() and database functions

I'm creating a TV Guide which lists programmes coming up (and on some listings, previous airings from the past), with all data stored in a database. It runs in PHP, my version being 5.28 (upgrading to 5.30 or 6 soon).
Below is a script which works (note the field airdate is stored as DATETIME in the database):
[Disclaimer: The script isn't mine, but a generic one I downloaded, and modified to suit my own needs.]
<? //connect to mysql //change user and password to your mySQL name and password
mysql_connect("localhost","root","PASSWORD");
//select which database you want to edit
mysql_select_db("tvguide1");
//select the table
$result = mysql_query("select * from epdata3 order by airdate LIMIT 20;");
//grab all the content
while($r=mysql_fetch_array($result))
{
//the format is $variable = $r["nameofmysqlcolumn"];
//modify these to match your mysql table columns
$programme=$r["programme"];
$channel=$r["channel"];
#$airdate = strtotime($r['airdate']);
$airdate = strtotime($r['airdate']);
$now = strtotime("NOW");
$currentYear = date("Y", $now);
$yearOfDateFromDatabase = date("Y", $airdate);
if($yearOfDateFromDatabase == $currentYear)
$dateFormat = "F jS - g:ia"; // dateFormat = 24 December
else
$dateFormat = "F jS, Y - g:ia"; // dateFormat = 01 January 2010
$currentTime = date("g:ia", $airdate); // format of "Y" gives four digit year ie
2009 not 09
$airdateFormatted = date($dateFormat, $airdate);
$sDate = date("F dS, Y - g:ia",$airdate);
$episode=$r["episode"];
$setreminder=$r["setreminder"];
echo "<tr><td><b>$programme</b></td><td>showing on $channel</td>";
echo "<td>$airdateFormatted</td><td>$episode</td><td>$setreminder</td></tr>";
}
?>
That displays all the episodes coming up, and if there's any coming up the next year, it displays them with the year, like this:
TV Programme showing next on Channel1 December 30th, 2009 - 6:00pm "Episode 1 - Photosynthesis" Set Reminder
TV Programme showing next on Channel1 January 6th - 2:45pm "Episode 2 - Behind the Music" Set Reminder
TV Programme showing next on Channel1 January 7th - 8:00pm "Ultimate Car Crimes" Set Reminder
However, what I would like it to do is remove certain records after a period of time has expired (but that would have to be set somewhere in the script, since programme lengths vary) rather than me manually deleting them from the database. Some programmes are 30 minutes long, others 60 minutes... lengths vary, basically.
What I would like it to do is this (notice that the first listing does not show the date as it is the current date.):
TV Programme showing next on Channel1 6:00pm "CCTV Cities - Wigan" Set Reminder
TV Programme showing next on Channel1 January 9th - 2:45pm "Roman Empire - A History of its People" Set Reminder
TV Programme showing next on Channel1 January 10th - 8:00pm "Celebrity 100 Worst Moments" Set Reminder
but I don't know how to configure it to do this with PHP or the date() function. It works fine with the dates, and showing them.
I don't have access to cron jobs since this is on a localhost Apache installation on Windows Vista Home Edition.
If anyone could help me figure this out it would be much appreciated - all help is much appreciated.
I haven't put this as a live site, since it's "in development hell" right now, and I want to get things right as much as possible.
Your question is a bit unclear, but I assume you are asking how you can select only episodes from today or future, and how to format the date so that when the episode is airing today, show only the date.
Here's a revised version of your code that can handle both of those:
<?php
//connect to mysql
mysql_connect("localhost","root","PASSWORD");
mysql_select_db("tvguide1");
// Select only results for today and future
$result = mysql_query("SELECT * FROM epdata3 WHERE airdate >= CURDATE() ORDER BY airdate ASC LIMIT 20;");
while($r = mysql_fetch_array($result)) {
$programme = $r["programme"];
$channel = $r["channel"];
$airdate = strtotime($r['airdate']);
$episode = $r["episode"];
$setreminder = $r["setreminder"];
$now = time();
if(date('Y-m-d') == date('Y-m-d', $airdate)) {
// Same date, show only time
$dateFormat = 'g:ia';
} elseif(date('Y') == date('Y', $airdate)) {
// Same year, show date without year
$dateFormat = 'F jS - g:ia';
} else {
// Other cases, show full date
$dateFormat = 'F jS, Y - g:ia';
}
$airdateFormatted = date($dateFormat, $airdate);
echo "<tr><td><b>$programme</b></td><td>showing on $channel</td>";
echo "<td>$airdateFormatted</td><td>$episode</td><td>$setreminder</td></tr>";
}
?>
MySQL can literally handle millions of records - why bother deleting when you can archive..? Just don't show the archived records.
for listing future records instead of this:
$result = mysql_query("select * from epdata3 order by airdate LIMIT 20;");
I would suggest something like this:
$result = mysql_query("select * from epdata3 WHERE airdate > '$today' ORDER BY airdate LIMIT 20;");
For a gig listing page I years ago also added a delete algorythm fearing the db could get 'full' - but regretted it later...
function reldate ($time) {
$now = time();
$cmp_fmt = '%Y%m%d';
if (strftime($cmp_fmt, $time) == strftime($cmp_fmt, $now)) {
$out_fmt = '%I:%M %P';
} else {
$day = strftime('%e', $time);
if (preg_match('/([^1]1|^1)$/', $day)) {
$day_suffix = 'st';
} elseif (preg_match('/([^1]2|^2)$/', $day)) {
$day_suffix = 'nd';
} elseif (preg_match('/([^1]3|^3)$/', $day)) {
$day_suffix = 'rd';
} else {
$day_suffix = 'th';
}
$out_fmt = '%B %e' . $day_suffix . ' - %I:%M %P';
}
return strftime($out_fmt, $time);
}

Categories