Building future date array - php

I am building an interactive web form where after user logs in, they can choose to pay toward their account...either every (n)th day of the month OR every 'n' number of days - and they will choose how many payments they'd like to do
They will use datepicker to choose their starting date (which can never be sooner than tomorrow)
I want to pass these parameters to a php script and then render a page that says they have agreed to make x number of payments on the following dates....
I'm having a problem getting the math right that I pass to this script.
i.e. if they choose to make 6 payments every 14 days starting on 6/25/2017 for example....how do I put this in an array and have the resulting page say: you've agreed to pay x amount on:
06/25/2017
07/09/2017
07/23/2017
08/06/2017
08/20/2017
09/03/2017
etc
They can choose a minimum of 1 payment date or up to a max of 12 payment dates. Can someone steer me in the right direction on building the array?

You should add x days to your inicial date, one way is:
$next = date("Y-m-d", strtotime('+ 14 days', strtotime($initialdate)));

Give this a shot...
<?php
// the date the user selected
$selectedPaymentDate = strtotime('2017-06-24');
// the frequency a user will pay
$freqNum = 14;
$freqType = 'days'; // days, months, years, whatever `strtotime` will handle
// the total number of payments a user must make
$totalPayments = 6;
// where we'll keep the dates
$paymentDates = [];
// build the dates array
for($i = 0; $i <= $totalPayments; $i++){
$next = ($freqNum * $i);
$paymentDates[]= date('Y-m-d', strtotime("+{$next} {$freqType}", $selectedPaymentDate));
}

Related

PHP: How calculate calendar days with all 42 days

The goal is exclusively to get a range of days, in other words
, start date and end date, as if it were a "calendar matrix", containing the 42 days, being the days of the current month, with the days of the previous month and next month. No need to present (render) a calendar, only get dates.
For example, follow image below.
I need to enter a certain month of a given year, and would need to get this range of days, as picture.
Using PHP Carbon, I easily get the days of the current month, using startOfMonth(), endOfMonth() , subMonth(), addMonth().
Doing this, I get every day of these 3 months, but the goal is to be able to "filter" these days to present only the interval equal to a calendar, but obviously something dynamic, ie, if I use Carbon, would simply inform the desired date , and get "filtered" range, respecting the position of each "cell".
$prev_start = Carbon::now()->subMonth()->startOfMonth();
$prev_end = Carbon::now()->subMonth()->endOfMonth();
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$next_start = Carbon::now()->addMonth()->startOfMonth();
$next_end = Carbon::now()->addMonth()->endOfMonth();
So here's what you can do:
$monthStart = Carbon::now()->startOfMonth();
$monthEnd = Carbon::now()->endOfMonth();
$calendarStart = $monthStart->startOfWeek(Carbon::SUNDAY);
$calendarEnd = $monthEnd->endOfWeek(Carbon::SATURDAY);
$calendarStart and $calendarEnd should now contain the first and last day that will be displayed in a single screen. This assumes that the calendar will expand the first and last week displayed.
If you are using a calendar that always shows 42 days regardless you can just do:
$monthStart = Carbon::now()->startOfMonth();
$calendarStart = $monthStart->startOfWeek(Carbon::SUNDAY);
$calendarEnd = $calendarStart->addDay(42);

Get random number from array every 24 hours

I would like to know if it would be possible to retrieve a value from an array and use that value for the entire day without changing the value on refresh, it will be used for a discount section. So everyday one of the random values will be taken and that value will be applied as discount % for the next 24 hours. Tomorrow (24 hours later) it will take another value and use that value for the next 24 hours.
I created a logical statement below but isn't working. Any help will be gladly appreciated to complete below function.
//TIME VALUES
date_default_timezone_set('Asia/Dubai');
$currentTime = date('H:i');
$dayStartTime = '00:01';
$dayEndTime = '23:59';
if($currentTime >= $dayStartTime && $currentTime <= $dayEndTime) {
$items = Array("10","15","20");
echo $items[array_rand($items)];
}
Thank you for you time.
Dane
I think you'll want to store a discount somewhere. This will at minimum have 2 fields: amount and expiry.
On load, check if there's a valid discount:
SELECT * FROM discounts WHERE expiry > NOW() LIMIT 1;
If a result is returned, use it. If not, create a new discount with an expiry of 24 hours and use that.

Monthly Commission Calculation PHP

I'm running into a coder's block with PHP dates. Let me first paint the picture of what I want to happen. ex:
$user_join_date = new DateTime('2015-01-31');
$today_date = new DateTime('2015-04-30');
Every day a cron will be run and for this example, on every 31st (or 30th - 28th depending on the month) the system will calculate commission for this user based on orders and volume from the past month BETWEEN '2015-03-31' AND '2015-04-29'.
So what I need is two fold. First, I need to make sure I'm calculating the commission on the correct day ie: the monthly anniversary of their join date OR that same month's equivalent. Second, I need to find the time frame in between which I'll calculate commissions as demonstrated in the mysql snippit above.
For obvious reasons I can't just say:
if ($user_join_date->format('d') == $today_date->format('d')){
calc_commission();
}
Because this wouldn't get run every month. Let me know if I'm unclear on anything.
I think you're saying you want to credit each user on an integral number of months since her signup date. There's an aspect of MySQL's date arithmetic you will find very convenient -- INTERVAL n MONTH addition.
DATE('2015-01-30') + INTERVAL 1 MONTH ==> '2016-02-28'
DATE('2016-01-30') + INTERVAL 1 MONTH ==> '2016-02-29'
This feature deals with all the oddball Gregorian Calendar trouble around weekdays, quite nicely. I'm going to call the date the renewal date.
Now, let us say that the column signup contains the date/time stamp for when the user signed up. This expression determines the most recent monthly renewal date. In particular, if it is equal to CURDATE(), today is the renewal date.
DATE(signup) + INTERVAL TIMESTAMPDIFF(MONTH, DATE(signup), CURDATE()) MONTH
Next: This closely related (duh!) expression is equal to the previous month's renewal date.
DATE(signup) + INTERVAL TIMESTAMPDIFF(MONTH, DATE(signup), CURDATE())-1 MONTH
You could just take CURDATE() - INTERVAL 1 MONTH but this is much more accurate around Gregorian month-end monkey business. Try it: it works right even at the end of February 2016 (leap year day).
Now, you'll want to use transactions that happened beginning on the previous renewal date >=, up until the end of the day before < the present renewal date, in your computation. In MySQL filtering by that date range looks like this.
WHERE transdate >= DATE(signup) +
INTERVAL TIMESTAMPDIFF(MONTH, DATE(signup), CURDATE())-1 MONTH
AND transdate < DATE(signup) +
INTERVAL TIMESTAMPDIFF(MONTH, DATE(signup), CURDATE()) MONTH
$base_dt is your joining date. So If you pass it to checkIt function It will provide you true or false accordingly today's day is billing day or not.
$base_dt = new DateTime('2015-04-30', new DateTimeZone("America/Chicago"));
if(checkIt($base_dt)) {
echo "true";
//this is the day.
} else {
echo "false";
//this is not the day.
}
So the check it function should be like this .....
function checkIt($base_dt) {
$base_d = $base_dt->format('j'); //without zeroes
echo $base_d;
$today = new DateTime('now');
$d = $today->format('j');
echo $d;
if($base_d == $d) {
return true;
} else if($base_d>28) {
$base_dt->modify('last day of this month');
$dif_base = $base_dt->format('j') - $base_d;
//echo $dif_base;
$today->modify('last day of this month');
$diff_today = $today->format('j') - $d;
//echo $diff_today;
if(($base_d==31 && $diff_today==0)||($base_d==30 && $diff_today==0 && $d<30)||($base_d==29 && $diff_today==0 && $d<29)) {
return true;
}
if($dif_base==0 && $diff_today==0) {
return true;
}
}
return false;
}

Calculating Total Overtime Working Hours using Condition

Need your help with my case.
How to make calculating total overtime working hours using condition ?
Example :
using input type,
OT From <input type="text" name="ot_from">
OT To <input type="text" name="ot_to">
Total Hours <input type="text" name="total_hours">
Working days : from 08.00 - 17.00 (normal working days)
If I working until 19.00, should be calculate that I do overtime for 2 hours.
In my rules, from 18.00 - 18.30 not calculate overtime because that's a break time.
So should be my total Overtime hours is 1.5 not 2 hours.
Someone can give me a solution ?
Appreciate your help.
Thank you.
David
Here is what you should do:
1 Split the hours and minutes into a total amount of minutes.
str = "1:23" or other time value
time = parseInt(str.split(":")[0], 10)*60+parseInt(str.split(":")[1], 10)
2 Subtract the finish time from the start time - this will give you the final time.
3 To convert from minutes to hours do the following:
minutes = time%60
hours = parseInt(time/60, 10)
You don't actually need PHP - this can all be done with Javascript, as long as you are not looking to store the data in a database or anything.
If you want to make sure the input of the user is always equal, you should replace the input fields with Select boxes. Then you can make one Select box for the hours and one for the minutes.
To calculate the working hours, you can do a basic calculation like this:
<?php
// Vars of the POST form
$otfrom_hours = $_POST['ot_from_hours'];
$otfrom_minutes = $_POST['ot_from_minutes'];
$otto_hours = $_POST['ot_to_hours'];
$otto_minutes = $_POST['ot_to_minutes'];
// Make a full string for strtotime
$otfrom_string = $otfrom_hours.":".$otfrom_minutes;
$otto_string = $otto_hours.":".$otto_minutes;
// Basic calculation
$start = strtotime($otfrom_string);
$end = strtotime($otto_string);
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>
Hope it will be usefull!

calculation of 'work time' and 'lunch time' for each day - php/mysql

All employees in/out data entry is fetching in this format:
logtype time Date
------------------------------------------------------
start_time [come office] 10:30 11-11-2010
end_time [go to lunch] 14:00 11-11-2010
start_time [come back from lunch] 15:00 11-11-2010
end_time [out from office] 20:00 11-11-2010
Question:
how can I calculate 'start time', 'end time', 'total time including lunch time' and 'total time excluding lunch time'
start time
end time
total time including lunch time
total time excluding lunch time
I've thought about it, and I don't see a way of doing this without iterating each item and making the calculations yourself. You could add a "Day" column (e.g. DAYOFMONTH, DAYOFWEEK, or DAYOFYEAR) then begin going over the login/logout times by "time" ascending. The only problem would be "open-ended" times (scenarios where a user didn't punch in/out).
Most time tables I've seen has eliminated this with using (typically) 4 columns.
Work_Day
Login_Time
Logout_Time
Hours_Worked
Then you can conclude if there was a value missing (one of the time fields would be NULL) and can do a quick query against the table for number of hours worked (or on a weekly bases with a quick column addition using Work_Day as the root of the calculation).
To answer the original question though, the pseudo-code would go something like this:
// $query = mysql_query(....) // <-- populate this
$times = Array('start'=>null,'end'=>null);
$result = Array('start_time'=>null,'end_time'=>null,'total_wo_lunch'=>0,'total_w_lunch'=>0);
while ($log = mysql_fetch_array($query)){
{
$_ = $log['date'].' '.$log['time'].':00';
$_datetime = strtotime($_);
if (is_null($result['start_time'])) $result['start_time'] = $_datetime;
else $result['end_time'] = $_datetime;
if (is_null($times['start'])) $times['start'] = $_datetime;
else if (is_null($times['end'])) {
$times['end'] = $_datetime;
$diff = ($times['end']-$times['start'])/3600; // convert to hours
$result['total_wo_lunch'] += $diff;
$times['start'] = null;
$times['end'] = null;
}
}
$result['total_w_lunch'] = ($result['end_time']-$result['start_time'])/3600; // convert to hours
print_r($result);
EDITv2
This is an update with code that works. My only issue here is with a bit of rounded on the time card (the worked 8.5 hour day is coming in at 8.53, though I don't see why. Same with the overall 9.5 hour day). other than that it seems to work fine. Let me know if you'd like to see other changes, and my apologies for posting untested code. I was more-or-less going for conceptual.

Categories