incrementing a date in a loop - php

I've done some reasearch but I did not find any issue. I try to increment a date in a loop in order to test if some files does exist. In fact I would like to make some user play each sevent days. When they played the file is created whith their IP and with the date. So we test in a loop if a file does exist with each date between this days. If it exist we return 1 else we return 0.
I met some trouble I do not really know how to increment a date in php using aloop
I tried something like that
**function afficheTirageAusort() {
//Initialisation des variables
$ip = $_SERVER["REMOTE_ADDR"];
$date_str = date('d-m-y');
$rep = "ip/";
if (!file_exists($rep)) {
fopen($rep, "w+");
}
$fichier = $ip . $date_str . '.txt';
$periode = 7;
$i = 0;
$date_jeu = 0;
//Test de l\'existence du fichier
while ($i <= $periode) {
list($d,$m,$Y)= explode('-',$date_str);
$date2 = Date('d-m-Y', mktime(0, 0, 0, $m, $d + 1, $Y));
$date = Date($date2, mktime(0, 0, 0, $m, $d + 1, $Y));
var_dump($date);
if (file_exists($rep . $ip . $date . '.txt')) {
$var = 0;
} else {
fopen($rep . $ip . $date . '.txt', 'w+');
$var = 1;
//break 1;
}
$i++;
};
return $var;
}
I'm a beginner in php.
anykind of help will be much appreciated.

You will want to use strtotime and continue to use the $date variables:
// Setup the dates
list($d, $m, $Y) = explode('-', $date_str);
$date2 = Date('d-m-Y', mktime(0, 0, 0, $m, $d, $Y));
$date = Date($date2, mktime(0, 0, 0, $m, $d, $Y));
//Test de l\'existence du fichier
while ($i <= $periode) {
$date = strtotime("+1 day", strtotime($date)); // 1 day past previous date
$date2 = strtotime("+1 day", strtotime($date)); // 1 Day past the $date var
echo date("Y-m-d", $date);
var_dump($date);
if (file_exists($rep . $ip . $date . '.txt')) {
$var = 0;
} else {
fopen($rep . $ip . $date . '.txt', 'w+');
$var = 1;
//break 1;
}
$i++;
};
return $var;

try something along these lines.
$todaysdate = date("Y-m-d H:i:s");
$tomorrowsdate = date("Y-m-d H:i:s", date()+86400);
essentially i just added 86400 seconds to the current date, and there are 86400 seconds in a day, so I just added 1 day.

Wouldn't it be easier for you to create date out of UNIX Timestamp and increment it? Like this:
$time = time() + (3600 * 24);
$date = date('d-m-Y', $time);

Related

installment due by period - PHP

the code snippet below shows a simulation of installments, with fixed expiration dates, divided every 30 days!
I would like to include a periodic expiration date, for example, every 20 days, or 10 every 10, depending on the variable $periodicity;
I have no idea how to do it?
<?php
function calculate_due($num_installment, $first_due_date = null){
if($first_due_date != null)
{
$first_due_date = explode('/',$first_due_date);
$day = $first_due_date[0];
$month = $first_due_date[1];
$year = $first_due_date[2];
}
else
{
$day = date('d');
$month = date('m');
$year = date('Y');
}
$periodicity = 20;
for($installment = 0; $installment < $num_installment; $installment++)
{
if ($periodicity == 30)
echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $day, $year))),'<br/>';
else
echo date('d/m/Y', strtotime('+'.$installment. " month", mktime(0, 0, 0, $month, $periodicity, $year))),'<br/>';
}
}
echo 'Calculates installments from an informed date<br/>';
calculate_due(5, '10/10/2020');
Try this,
<?php
function calculate_due($num_installment, $first_due_date = null, $days = 1){
$start = DateTime::createFromFormat('d/m/Y', $first_due_date);
$end = DateTime::createFromFormat('d/m/Y', $first_due_date);
$end->add(new DateInterval('P'.($num_installment * $days).'D'));
$period = new DatePeriod(
$start,
new DateInterval('P'.$days.'D'),
$end
);
$return = [];
foreach ($period as $date) {
$return[] = $date->format('d/m/Y');
}
return $return;
}
echo 'Calculates installments from an informed date<br/>'.PHP_EOL;
echo implode("\n", calculate_due(5, '10/10/2020', 20));
https://3v4l.org/TLR8a
Change 20 (the last function parameter) to suit the number of days between.
Result:
Calculates installments from an informed date<br/>
10/10/2020<br/>
30/10/2020<br/>
19/11/2020<br/>
09/12/2020<br/>
29/12/2020<br/>

Transform PHP script to a general-case function

I have this code that modify date in the way I want, for example, if starting date is 31/01/2000, adding 1 month will return 29/02/2000, then, 31/03/2000.
If date is 30/01/2000 (not last day of the month) it will return 29/02/2000, then 30/03/2000, 30/04/2000 and so on.
I want to transfirm that code in a general case function, to be able to add 1,3,6,12 months, and inside the for loop, to work all corect.
I would like it to be a function 2 or 3 arguments, startingDate, duration(nr of iterations), frequency (add 1/3/6/12 months per once).
<?php
$date = new DateTime('2000-01-28'); // or whatever
#echo $date->format('d')." ".$date->format('t');
$expectedDay = $date->format('d');
$month = $date->format('m');
$year = $date->format('Y');
for ($i = 0; $i < 100; $i++) {
echo $date->format('Y-m-d') . "<br>";
if ($month++ == 12) {
$year++;
$month = 1;
}
$date->modify("${year}-${month}-1");
if ($expectedDay > $date->format('t')) {
$day = $date->format('t');
} else {
$day = $expectedDay;
}
$date->modify("${year}-${month}-${day}");
}
Whelp, there's an extremely easy function for this in PHP nowadays.
first, you get a timestamp instead of a datetime:
$timestamp = $date->getTimestamp();
Now, just use strtotime to add onto the date.
strtotime("+1 month", $myTimestamp);
You can change the +1 into anything you want, so you just throw the amount in the string and voila; a dynamic way of adding them!
however, since you want to do +30 days instead of a natural month, you're better off just adding 30 days to the timestamp, like so:
$timestamp = $timestamp + (3600 * 24 * 30); //s per h * h per d * d
So, you'd end up with something like this:
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$timeToAdd = (3600 * 24 * 30) * $frequency; //30 days * frequency
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$newDate = $previousDate + (3600 * 24 * 30);
$return[] = date('Y-m-d', $newDate);
$previousDate = $newDate;
}
return $return;
}
And then for the rendering part:
//Let's render this stuff
$dates = calculateTime('24-08-2017', 25, 3);
foreach($dates as $date){
echo "$date</br>";
}
If you'd like to do it with full months, something like this:
<?php
function calculateTime($startingDate, $iterations, $frequency){
$timeStamp = strtotime($startingDate);//if you expect a string date
$return = array();
$return[] = date('Y-m-d', $timeStamp); //Original date
$previousDate = $timeStamp; //Original date for now
for($i = 0; $i < $iterations; $i++){
$lastDay = false;
//It's the last day of the month
if(date('t', $timeStamp) == date('d', $timeStamp)){
$lastDay = true;
}
if($frequency == 12){
$newDate = strtotime('+1 year', $previousDate);
}
else{
if($lastDay){
$firstDayOfMonth = strtotime(date("01-m-Y", $previousDate));
$newDate =strtotime("+$frequency month", $firstDayOfMonth);
}
else{
$newDate = strtotime("+$frequency month", $previousDate);
}
}
if($lastDay){
$return[] = date('Y-m-t', $newDate);
}
else{
$return[] = date('Y-m-d', $newDate);
}
$previousDate = $newDate;
}
return $return;
}
//Let's render this stuff
$dates = calculateTime('31-01-2000', 25, 1);
foreach($dates as $date){
echo "$date</br>";
}
I hope this helps? :)
If you'd like to see how this works quickly, just paste my code into a phpfiddle. Unfortunately the save function is broken right now.

Calculate days in months between two dates with PHP

I have a period with startdate of 2016-12-26 and end date 2017-03-04.
Now I would like to find out how many days in each months there is, from a given period. Expected output from the above period dates (array):
2016-12: 5
2017-01: 31
2017-02: 28
2017-03: 4
How can I accomplish this cleanest way? I have tried to:
first looking at the period_start, get the days = 26 and
find out the start/end dates of the months between 2016-12 and 2017-03, to then calculate the days here (31 respectively 28 in february)
then finally calculating the 4 days in 2017-03.
But is there any cleaner/better way?
This can be achieved easily using the DateTime class. Create the objects, and use DateTime::diff() on them, then use the days property.
$start = new DateTime("2016-12-26");
$end = new DateTime("2017-03-04");
echo $start->diff($end)->days; // Output: 68
Live demo
http://php.net/datetime.construct
#Karem hope this logic will help you, this is working case for all your conditions please try this below one:
<?php
$startDate = '2016-12-26';
$endDate = '2017-03-04';
$varDate = $startDate;
while($varDate < $endDate){
$d = date('d', strtotime($varDate));
$Y = date('Y', strtotime($varDate));
$m = date('m', strtotime($varDate));
$days = cal_days_in_month(CAL_GREGORIAN,$m,$Y);
$time = strtotime($varDate);
if($varDate == $startDate){
$time = strtotime(date('Y-m-01', $time));
$days = $days - $d;
}
else if(date("Y-m", strtotime($varDate)) == date("Y-m", strtotime($endDate))){
$days = date("j", strtotime($endDate));
}
echo date('Y-m', strtotime($varDate)). ": ".$days."<br>";
$varDate = date('Y-m-d', strtotime("+1 month", $time));
}
This is long but easy to understand that how to achieve you your goal
<?php
function getMonthDays($start,$end){
if($start < $end){
$start_time = strtotime($start);
$last_day_of_start = strtotime(date("Y-m-t",$start_time));
$start_month_days = ($last_day_of_start - $start_time)/(60*60*24);
echo date("Y-m",$start_time).": ".$start_month_days."\n";
$days = "";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
while($start < $end){
$month = date("m",$start_time);
$year = date("Y",$start_time);
$days = date('t', mktime(0, 0, 0, $month, 1, $year));
echo date("Y-m",$start_time).": ".$days."\n";
$start = date("Y-m-d", strtotime("+1 month", $start_time));
$start_time = strtotime($start);
}
echo date("Y-m",strtotime($end)).": ".date("d",strtotime($end))."\n";
}else{
echo "Wrong Input";
}
}
getMonthDays('2016-12-26','2017-03-04');
?>
live demo : https://eval.in/781724
Function returns array : https://eval.in/781741
<?php
$d1 = strtotime('2016-12-26');
$d2 = strtotime('2017-03-04');
echo floor(($d2 - $d1)/(60*60*24));
?>
i used Carbon (https://carbon.nesbot.com/docs/) but you can do it with any other time lib.
$startDate = Carbon::createFromFormat('!Y-m-d', '2017-01-11');;
$endDate = Carbon::createFromFormat('!Y-m-d', '2018-11-13');;
$diffInMonths = $endDate->diffInMonths($startDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$start = $i == 0 ? $startDate->copy()->addMonth($i) : $startDate->copy()->addMonth($i)->firstOfMonth();
$end = $diffInMonths == $i ? $endDate->copy() : $start->copy()->endOfMonth();
echo $end->format('Y-m') . ' ' . ($end->diffInDays($start) + 1) . PHP_EOL;
}

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

PHP Get the year of most recent occurrance of specific date

I am working on a script that will determine when a specific calendar date most recently occurred.
This post, Get the year of a specified month in previous 12 months?, is the basis of my current beta. It was written for a monthly result and not a specific date.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time())
? mktime(0,0,0,$m,$d)
: mktime(0,0,0,$m,$d,date("Y") -1);
$from = date('F jS', $c) . " last occurred in " . date('Y', $c) . ".";
echo $from;
?>
The result of the default value, October 1 is:
"October 1st last occurred in 2012."
For June 11th, as a random example:
"June 11th last occurred in 2013."
All date results are TRUE, except for the result for February 29th:
"March 1st last occurred in 2013."
Obviously, this is a false statement since the desired result is:
"February 29th last occurred in 2012."
I'm kind of stuck, what is the best way to add a true leap year result?
This is calculating last true year. Replace with following codes.
<?php
if (empty($_GET['m'])) {
$m = "October";
} else {
$m = htmlspecialchars($_GET['m']);
}
if (empty($_GET['d'])) {
$d = "1";
} else {
$d = htmlspecialchars($_GET['d']);
}
date_default_timezone_set('America/Los_Angeles');
$y = date('Y');
if($m == "February" && $d == "29") $y = $y - ($y % 4);
$m = date('m', strtotime($m));
$c = (mktime(0,0,0,$m,$d) < time()) ? mktime(0,0,0,$m,$d,$y) : mktime(0,0,0,$m,$d,$y);
$from = date('F jS', $c) . " last occurred in " . $y . ".";
echo $from;
?>
Results
For 2013: Result 2012
For 2012: Result 2012
For 2011: Result 2008
For 2010: Result 2008
$month = 9;
$day = 1;
$timestamp = mktime(0, 0, 0, $month, $day);
if ($timestamp > time()) {
$timestamp = mktime(0, 0, 0, $month, $day, date('Y') - 1);
}
covert timestamp to your desire format.

Categories