php how to to do operation on date - php

I have problem when i want calculate date. Simple Example:
I have 2013-09-01 is start date and I have 30day per month. My work i need alert tell to my user in 10 day before end month(it's mean on 2013-09-20i must alert message it's 10day more for end of this month). So every one have any idea for help to calculate it. becuese i like can't (+, -, *,/) on date. Now i am some data like
<?php
date_default_timezone_set('Asia/Phnom_Penh');
$current = time();
$start = 1380188957;
echo 'Start date: '. date('Y-m-d', $start) ."\n";
echo '<br/>';
$repeat = 30;
$enddate = time() + ($repeat * 24 * 60 * 60);
echo 'end date: '. date('Y-m-d', $enddate) ."\n";
Thanks in advent for helping.

Not every month has 31 days, you can get the number of days in any month by using the t option for the string format param in php's date() function.
// Current time as unix timestamp
$now = time();
// Number of days in current month
$days_this_month = date("t", time());
// Last day of the current month as a unix timestamp;
$end_of_month = strtotime(date("Y-m-t", time()));
// Ten days before the end of the month as a unix timestamp
$ten_days = strtotime('-10 days', $end_of_month);
Now we can do a check to see if it is 10 days before the end of the month:
if($now > $ten_days) {
// Do something
}

$start = 1380188957;
$enddate = time() + ($repeat * 24 * 60 * 60);
That's your own code. Using that we can easily compute 10 days before end date
$alert=$enddate-864000; // That's 10 days
$alertdate=date('Y-m-d', $alert);

Related

Calculate percentage between dates in php

I want to calculate the percentage (from 0 to 100) of the time elapsed between two dates (start and end) according to the current date.
For example:
$start_date = "01/01/2018";
$end_date = "31/12/2018";
$today = "30/06/2018";
Expected output:
Percentage: 50
Any idea? Thanks
You could convert all dates to timestamps and do the math from there. strtotime() will convert the dates for you, but that will interpret your dates with slashes in the english format (MM/DD/YYYY) instead of (DD/MM/YYYY). If you replace the slashes with dashes, it will read it in the DD-MM-YYYY format.
$date_timestamp = strtotime(str_replace('/', '-', $date));
Then it's just a matter of:
$total = $end_date - $start_date;
$part = $todays_date - $start_date;
$percent = $part/$total * 100;
You'd need at least three variables:
$fromDate = strtotime("01/01/2018 ");
$currentDate = time();
$toDate = strtotime("01/01/2019");
//days between From and To
$datediffA = round(($toDate- $fromDate) / (60 * 60 * 24));
//days between From and Current
$datediffB = round(($currentDate- $fromDate) / (60 * 60 * 24));
echo $datediffA;
echo $datediffB;
Will output:
365
320
Now knowing these numbers you can go on and find the percentage of one to another.
$percentage = ($datediffB*100)/$datediffA;
echo $percentage;
Will output:
87.671232876712%
Date("z") gives you the day of the year.
Your "today" returns 180.
If we assume start and end is the start and end of current year then all you need is the date("z") to calculate the percentage.
Round the value to desired format and echo the percentage.
$today ="30/06/2018";
echo round(date("z", strtotime(str_replace("/", "-", $today)))/365*100,0) . "%";
// 49%
https://3v4l.org/EG6lt
I assume 365 days is enough accurate as a year.
You can use 365 + date("L") instead of only 365 in the code above and it will add one if it's a leap year.
Meaning:
echo round(date("z", strtotime(str_replace("/", "-", $today)))/(365 + date("L"))*100,0) . "%";

Add multiple of interval to date until date is in current year

suppose I have an initial date whose year was prior to that of the current year and I want to repeat the event every 7 days but only in the current year.
How would I find the first occurrence in the current year?
I realize I can do it with a loop like this:
$reOccurringEvent =new DateTime('2013-12-01');
$interval = new DateInterval('P7D');
while($reOccurringEvent->format('Y') < date('Y') ){
$reOccurringEvent->add($interval);
}
echo $reOccurringEvent->format('d m Y'); //05 01 2014
But it strikes me there should be a more efficient way to achieve this rather than repeatedly adding an interval to the date (it would happen many times if the initial date was some years ago).
I was hoping to be able to calculate the number of times the interval should be added and just do it a single time.
I was thinking something like:
$date = new DateTime();
$diff = $date->diff($reOccurringEvent)->days%7;
But obviously that doesn't work and I can't quite figure out the logic of how to do it.
More generically, the algorithm would be to find the number of intervals between the given date and the last day of last year. Then multiplying the interval by the number of intervals + 1 to get the first interval of the current year.
$date1="12/9/2013";
$ts1 = strtotime($date1);
$ts2 = strtotime("12/31/" . Date("Y")-1);
//get the number of seconds between the date and first of the year
$seconds_diff = $ts2 - $ts1;
echo "$seconds_diff <br>";
//get the number of days
$dayDiff=$seconds_diff/86400;
//how many intervals?
$intervalDays = "10";
//get the number of intervals from start date to last day of last year
$numIntervals = floor($dayDiff/$intervalDays);
echo $numIntervals."<br>";
//now the total intervals to get into the current year is one more interval, turn this into days
$totIntervals= ($numIntervals* $intervalDays)+$intervalDays;
//Date Time date in question
$theDt = new DateTime($date1);
//Add the intervals we calculated to the date in question, and we have the first date of the interval for the current year...
$theDt->add(new DateInterval('P' . $totIntervals. 'D'));
echo "The first date of the intreval is: " . $theDt->format('Y-m-d');
I think, if you are doing 7 day intervals, you can find out the Day of week of your initial date, and then get the first date of the current year with that day of week...
Find out day of week: How to find the day of week from a date using PHP?
Find out date with that day of week for this year: Getting first weekday in a month with strtotime
Putting it together:
$date=Date("2/8/2012");
//Get the day of week for the date in question
$dayOfWeek = date('l', strtotime($date));
echo "The day of week for the given date is: $dayOfWeek <br>";
//Get the current year
$thisYear = date("Y");
echo "This year: $thisYear <br>";
//Create a date with the first occurence of the day of week of the given date for the current year
$firstOccurenceThisYear = date("m/d/y", strtotime("January " .$thisYear ." " . $dayOfWeek));
echo "The first interval of the year is: $firstOccurenceThisYear";
/*
Output:
This year: 2014
The day of week for the given date is: Wednesday
The first interval of the year is: 01/01/14
*/
Here is a slightly modified version of #Dan's second answer which worked well for me.
Benchmarks shown below.
$date="1985-02-18";
$intervalDays = "5";
//original version
$benchMark = microtime(true);
$dt1 = new DateTime($date);
$interval = new DateInterval("P{$intervalDays}D");
while ($dt1->format('Y') < date('Y')) {
$dt1->add($interval);
}
echo $dt1->format('d m Y') . '<br>';
echo microtime(true)-$benchMark.'<br>';
//new version
$benchMark = microtime(true);
$dt1 = new DateTime($date);
$dt2 = new DateTime("12/31/" . ((int) Date("Y") - 1));
$dayDiff = $dt1->diff($dt2)->days;
$numIntervals = floor($dayDiff / $intervalDays);
$totIntervals = ($numIntervals * $intervalDays) + $intervalDays;
$dt1->add(new DateInterval('P' . $totIntervals . 'D'));
echo $dt1->format('d m Y').'<br>';
echo microtime(true)-$benchMark.'<br>';
exit;
output
02 01 2014
0.0145111083984
02 01 2014
0.000123977661133

PHP Date : get date different in years

this is my code:
date_default_timezone_set('Asia/Kuala_Lumpur');
$date_join = $row['date_joined']; =produce 2012-09-03
$today = date("Y-m-d"); = produce 2014-08-29
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$a, **$xxx**);
how can i get date durations ($today - $date_join) in years like :
Date of services : 1.5 years
You can use PHP strtotime() function. Try like this..
$join_date = '2012-09-03'; //join date
$today = date("Y-m-d"); //current date
$date_join = strtotime($join_date); // join date to seconds
$today = strtotime($today); //current date to seconds
$differenceInSeconds = $today - $date_join; // Time difference in seconds
echo number_format($differenceInSeconds / (365 * 24 * 60 * 60), 2) . ' Year(s)';
Get time difference in seconds from two dates
Divide the difference by one year equivalent seconds

PHP get date after one week and calculate the number of days left

I have a dynamic date, now what i want is that finding the date after exact one week, i have achieved that with the code below, but now i want that now many days are left for that week after date to come. i have got some sort of time stamp, but i don't know how to convert it to DAYS LEFT.
$weekDate = date( "d/m/Y", strtotime("19-05-2014") + 86400 * 7 );
echo $weekDate;// THATS PERFECT
////////////////////////////////////////////////////////////////
$future = strtotime( $weekDate ); //Future date.
$datediff = time() - $future;
$days = floor( ( ( $datediff / 24 ) / 60 ) / 60 ); //this is not perfect, returns some
sort of timestamp
I have tried other methods which are fine, but if week completes on 26, and today is 25th it gives me 0 days left, but it should say 1 day left. please help me.
In your $date_diff now is less than the future date thats why its zero. Inside strtotime() function, you can directly put a relative date inside. In this case, for one week you can use +1 week or +7 days. Consider this example:
$next_week = date('d/m/Y', strtotime('19-05-2014 +1 week')); // 26/05/2014
$next_week = strtotime('19-05-2014 +7 days');
$difference = $next_week - time(); // next weeks date minus todays date
$difference = date('j', $difference);
echo $difference . (($difference > 1) ? ' days ' : ' day ') . ' left';
// should output: 1 day left
Alright. I did something. Here's the code
$startDate = strtotime("19-05-2014");
$endDate = $startDate + 604800;
$diff = ($endDate - time()) / 60 / 60 / 24;
if ($diff < 1 && $diff > 0) {
$days = 1;
} else {
$days = floor($diff);
}
echo $days;
The problem you have with getting "1 day" if the date is tomorrow is the floor method. strtotime() gives you the time at 0 a.m. if you don't set it by your own. Because of that the difference between now and tomorrow is less than 1 which is 0 if you floor that. I created an if-clause for that.
But that will give you "1 day" for today and "1 day" for yesterday (last 2 days before the final date). If you want that better, you have to specify time in your initial date (19-05-2014).
Use DateTime for date and time calculations.
$weekDate = new \DateTime('+ 1 week');
$future = new \DateTime('+ 3 days');
$daysLeft = $weekDate->diff($future)->days;
echo $daysLeft; //4
See it working.
Reference http://php.net/datetime

Is current date within specified date/time range in PHP

I am creating a website that allow deliveries only within certain delivery time frames.
Here is an example of exactly what I'm looking for:
FakeCompany delivers on Wednesday and allows customers to place orders between Friday and Tuesday with a cutoff time of 11 PM on Tuesday night.
I need to figure out when the customer logs in if ordering is allowed (between Friday - Tuesday 11 PM). I also need to know how much longer they have to order.
I know the PHP date('N') function that Friday is 5:
date('N', strtotime('Friday'));
and Tuesday is 1:
date('N', strtotime('Tuesday'));
These time ranges may change, so I need a simple solution.
Here is what I started with, and now I'm lost on how to do this.
//Set today and get from database start / end days and end time
$today = (int)date('N');
$startDay = (int)date('N', strtotime('Friday'));
$endDay = (int)date('N', strtotime('Tuesday'));
$endDayTime = '11:00:00';
//If today is before start date
if($today >= $startDay && $today <= $endDay){
//This works only if the end date is not the following week
//It also needs to be before end day time!
}
I think I need to get the date of the week based on the DAY (Friday) and convert that to this weeks Friday if Friday has not passed or next weeks Friday and do the same with end date.
Then I need to know if today is between those dates / times.
$now = new DateTime();
$tuesday = new DateTime('last Tuesday');
$friday = new DateTime('Friday 11pm');
if ($tuesday < $now && $now < $friday) {
$interval = $friday->diff($now);
echo $interval->format('%d day %h hours %i minutes left to order');
}
else {
echo "you can't order now";
}
See it in action
Here is a function to check that today is an approved day then if its tuesday also make sure it is before 11pm:
/*
Acceptable days:
5 - friday
6 - saturday
7 - sunday
1 - monday
2 - tuesday
*/
//Can they order today?
if(in_array(date('N'),array(1,2,5,6,7))){
//if today is tuesday is it before 11pm?
if(date('N') == 2){
if(date('H')<23){
//23 = 11pm in 24 hour time
//Then can order
}
else{
//Then CANT order
}
}
//Its not tuesday so we dont care what time it is they can order
}
for the end day I think you could do it like this:
$endDay = (int)date('N', strtotime('Friday') + 3 * 24 * 3600 + 23 * 3600);
strtotime('Friday') to get friday and add 3 days of 24 hours to it, and it'll be Tuesday 0 am. Then you add 23 hours time to it as it finish at 11pm.
$today = (int)date('N');
$startDay = (int)date('N', strtotime('Friday'));
$endDay = (int)date('N', strtotime('Friday') + 3 * 24 * 3600 + 23 * 3600);
//If today is before start date
if($today >= $startDay && $today <= $endDay){
//now it works
}
Here is exactly what I am looking for.
The dates provided may not be this week or even this month, so we need to figure out based on the date what the day of the week was and set the date on this week or next week to same day depending on today (kinda confusing).
See It In Action
//IF USING A DATABASE TO STORE DATE/TIME
//Get route times
//When Using Database: $query = "SELECT * FROM routes WHERE id = '".$user['route_one']."'";
//When Using Database: $result = $this->query($query);
//When Using Database: $route = $this->fetchArray($result);
//Set date vaiables
$thisWeek = new DateTime();
$routeStart = new DateTime(date('Y-m-d H:i:s', strtotime('2013-04-21 00:00:00')));
//When Using Database: $routeStart = new DateTime(date('Y-m-d H:i:s', strtotime($route['start_time'])));
$routeEnd = new DateTime(date('Y-m-d H:i:s', strtotime('2013-04-24 00:00:00')));
//When Using Database: $routeEnd = new DateTime(date('Y-m-d H:i:s', strtotime($route['end_time'])));
$interval = $routeStart->diff($routeEnd);
$numDays = abs($interval->format('%d'));
//Check if today is past or on the start date, else start date is next week, and set day of week
if($thisWeek->format('N') >= $routeStart->format('N')){
$startDate = $thisWeek->modify('last '.$routeStart->format('l'));
}
else{
$startDate = $thisWeek->modify($routeStart->format('l'));
}
//Now that we know the start date add the amount of days to the start date to create the end date
$endDate = new DateTime($startDate->format('Y-m-d H:s:i'));
$endDate->modify('+'.$numDays.' days '.$routeEnd->format('H').' hours');
//Check to see if user is within the time range to order or not
$today = new DateTime();
if($startDate <= $today && $today <= $endDate){
//Find out how much longer ordering can take place
$interval = $endDate->diff($today);
$output = 'Allowed to order!<br>';
$output .= '<div id="orderTimeCounter">'.$interval->format('%d days %h hours %i minutes left to order').'</div>';
}
else{
//If today is before start date set start date to THIS week otherwise NEXT week
if($startDate >= $today){
$startDate = $startDate->modify('this '.$routeStart->format('l'));
}
else{
$startDate = $startDate->modify('next '.$routeStart->format('l'));
}
//Find out how much longer until ordering is allowed
$interval = $today->diff($startDate);
$output = 'Not allowed to order!';
$output .= '<div id="orderTimeCounter">'.$interval->format('%d days %h hours %i minutes until you can order').'</div>';
}
echo $output;

Categories