How to perform if statement for a certain timeperiod - php

I want to perform certain tasks in PHP between Monday 10:00am till Saturday 10:00am and I want to perform other tasks between Saturday 10:30am till Monday 10am. Every week.
I am sorry if that's a silly question. Any help would be highly appreciated.

if you are running a time triggered task run a cron job or if it is a user triggered like website and you want to change page according to day then use if else statement to select task.
you can get the time in weekday and hour:minute::second for if else selection using this
$d = new DateTime('Sunday,23:23:48 '); //set time day time format
echo $d->format('l , H:i:s ');
$date = new DateTime(); // get current datetime
echo $date->format('l , H:i:s '); //php get time in day time format
//output example Sunday , 23:23:48 Sunday , 23:34:47

$currentTime = time();
$time = date('H:i',$currentTime);
$date = date('h:i:s a', time());
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if ( ( ($day == "Sat") && ($time < 11) ) || ($day == "Mon" && $time > 9) )
{
# weekday then truncate table
}

Related

Find next recurrence of weekly event if PHP "N" date value is given

I have a weekday value available in the PHP date("N",$stamp) format + a time with an starting hour of an event. I want to show the date of next week if the event has started already and the date of this week if it is in the future. The time horizon is 7 days, so if "now" has passed, the expected recurrence is in 7 days.
Example
now() is tuesday, 2/10/2018, 13:00
$row['weekday'] = 2 (for tuesday)
$row['time'] = 13:01
$next should be 9/10/2018
vs.
now() is tuesday, 2/10/2018, 13:00
$row['weekday'] = 2 (for tuesday)
$row['time'] = 12:00
$next should be 2/10/2018
Here's the PHP documentation to the "N" time format:
N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)
I investigated quite a bit and could not find any solution to this. The only thing I found was this which I based the following (ugly, non-working) code on.
$next = (intval(date("N", strtotime("now"))) !== intval($row['weekday']))
?
(
date("d.m.Y", strtotime(
date("Y-m-d", strtotime("now")-strtotime("+". (date("w", strtotime("now")) +0) ." day"))
)+strtotime("+".$row['weekday']." day"))
)
:
(
(
(strtotime("now"))
<
(( strtotime(
date("Y-m-d", strtotime("now")-strtotime("+". (date("w", strtotime("now")) +0) ." day"))
)+strtotime("+".$row['weekday']." day")+strtotime($row['time'])))
)
?
(date("d.m.Y", strtotime("now")))
:
(date("d.m.Y", strtotime("now +1 week")))
)
)
Any ideas how to tackle this?
You should use \DateTime and not date():
$eventDate = \DateTime::createFromFormat("Y-m-d H:i:s", $date);
$today = \DateTime::createFromFormat("N", $weekDay);
$next = clone $today;
if ($today > $eventDate) {
$next->modify("+1 week"); //$next->add(new \DateInterval("P1W"))
//Eventually also set time
}
EDIT:
$now = new \DateTime();
$date = \DateTime::createFromFormat("D", "Tue"); //W and N are not working
$dayPeriod = new \DateInterval("P1D");
//Check if in last week
if ($date->format("W") < $now->format("W")) {
$date->add($dayPeriod);
}
//Check if in current week
if ($date->format("W") === $now->format("W")) {
$date->add($dayPeriod);
}
echo $date->format("Y-m-d");

PHP get yesterdays date unless weekend

I need to get yesterday's date to show the market close date. This only applies to Monday through Friday as the markets are not open on the weekend. Using this format how would I do that?
<?php
$yesterday = date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
echo $yesterday;
?>
Here's one way to do it:
$date= new \DateTime();
$oneDay = new \DateInterval('P1D');
$date->sub($oneDay);
if ('Sunday' === $date->format('l')) {
$date->sub($oneDay);
}
if ('Saturday' === $date->format('l')) {
$date->sub($oneDay);
}
echo $date->format('Y-m-d');
I just get today's date, subtract one day, and check to see if it is a Sunday. If so, subtract a day. Then I do the same thing for a Saturday. Ultimately you end up with the last weekday.
Keep in mind this is different then business day's as that Friday may be a holiday and the markets may be closed.
You could check what day the current week day is with date('w').
Note that Sunday is 0, and Saturday is 6.
And with that information, you can do:
$yesterday = strtotime(date('w') == 0 || date('w') == 6 ? 'last friday' : 'yesterday');
echo date('Y-m-d', $yesterday);
Basically, if it's a weekend, you ask for the last friday, otherwise, you ask PHP for yesterday.
If you don't like it in one line:
$w = date('w');
if($w == 0 || $w == 6)
$yesterday = strtotime('last friday');
else
$yesterday = strtotime('yesterday');
$yesterday = date('Y-m-d', $yesterday);
In our case today, Tuesday, June 14th 2016, it will return 2016-06-13.
For more information about the date function: http://php.net/manual/en/function.date.php

Alter date if it's a weekend date PHP

I have user defined date that I add one week to. I am trying to check the user's date and see if it's a Friday,Saturday,Sunday or Monday. If it is, then I want to loop until the date is a day other than those days (pseudo code below). The code I have doesn't actually seem to work.
$date = 10/10/2012;
while (date = friday, saturday, sunday, monday) {
$date = $date - 1;
}
Here is my code:
$postpone = date('Y-m-d', strtotime('+1 Week'));
$checkDate = date('w', strtotime($postpone));
while ($checkDate == 0 || $checkDate == 6 || $checkDate == 5 || $checkDate == 1) {
$postpone = date_sub($postpone,date_interval_create_from_date_string("1 day"));
$postpone = date("Y-m-d", $postpone);
$checkDate = date('w', strtotime($postpone));
}
Below code uses the object-oriented PHP methods to accomplish this. Note that it increments the date by 1 day and you can add or subtract any interval depending on how you want to reach your target weekday.
// Make sure to set timezone when using PHP DateTime
date_default_timezone_set('UTC');
// Create a new date set to today's date
$date = new DateTime;
// Add 1 week to the date
$date->add(new DateInterval('P1W'));
// Get a numeric representation of weekday for date (0-6 0=Sunday)
$weekday = $date->format('w');
// Loop while weekday is Fri, Sat, Sun, Mon
while ($weekday > 4 || $weekday < 2) {
// Add one day to date and get the weekday
$weekday = $date->add(new DateInterval('P1D'))->format('w');
}
echo $date->format('Y-m-d: w');

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;

Automatically Change Date Weekly (php)

Is it possible to update a date every week automatically with php?
For instance, I have a weekly forecast that is updated every Monday. The title would read something like "Forecast for Friday June 28th."
<h1>- Forecast for Friday June 28th -</h1>
Then on the following monday, I would like to automatically update the date in the title to the next occurring Friday.
is this possible with php?
This is what you're looking for:
switch (date('N'))
{
case 5:
$time = time();
break;
case 6:
case 7:
$time = strtotime('last Friday');
break;
default:
$time = strtotime('next Friday');
}
echo date('l F jS', $time);
Check the date function for different formatting options.
Although are you sure you want to wait until Monday until showing the forecast for the next Friday? Surely it should update to the following week on the Saturday (otherwise you'll be forecasting a past date)? If so, just remove the case 6/case 7 section.
Yes. Take a look at date() for formatting and strtotime() to quickly create relative timestamps:
The following should get you started:
echo date('l F jS', strtotime('monday'));
Note: If you're using PHP > 5.3 you should look at the DateTime class.
It's very simple coded to explain as much simple as possible. The script calculates how many days left until next Friday, if $today is not Friday.
Hope that helps you!
<?php
$now = time(); // current timestamp
$today = date("w", $now); // "w" returns the weekday (number)
$friday = 5; // 5th day of the week (sunday = 0)
if ($today == $friday) {
$ts = $now; // today is friday, don't change the timestamp
$daysLeft = 0; // no days left!
} else {
if ($today == 6) {
$daysLeft = 6; // saturday is bigger then friday
} else {
$daysLeft = $friday-$today; // get the left days
}
$ts = $now + 84600 * $daysLeft; // now + seconds of one day * days left
}
?>
<h1>
- Forecast for <?php echo date("D M d", $ts) ?>-
</h1>
$currDay = date('w');
$delta = $currDay==6 ? 6 : 5-$currDay;
$date = new DateTime();
$date->add(new DateInterval('P'.$delta.'D'));
echo $date->format('D M jS');

Categories