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');
Related
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
}
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
Using PHP, I'd like to get the dates for specific weekdays within a given number of weeks. For example, I want to get the dates for Monday, Wednesday and Friday from 10 weeks.
The pseudo code for what I want is like this:
function (monday, wednesday, friday, 10) {
// 10 is week numbers
week1 5,7,9 oct 2015
week2 12,14,16 oct 2015
...
week10
}
i write a solution for this. Thanks for all answers.
<?
$dates = array();
$i = 0;
while(true) {
$i++;
$time = strtotime("+$i days");
$dayOfWeek = date('w', $time);
if(
/*
0-sun
1-mon***
2-tue
3-wed***
4-thu
5-fri***
6-sat
*/
($dayOfWeek == 0) or
($dayOfWeek == 2) or
($dayOfWeek == 4) or
($dayOfWeek == 6)
) {
continue;
}
$dates[] = date('Y-m-d', $time);
if( count($dates) > 30 ) {
break;
}
echo json_encode($dates );
}
?>
Sounds like you want to work with schedules. I suggest you to have a look at library called When, it's "Date / Calendar recursion library for PHP 5.3+".
What you want to do is MWF schedule for next 10 weeks:
$now = new DateTime('NOW');
$after10Weeks = clone $now;
$after10Weeks->modify('+10 week');
$r = new When();
$r->startDate($now)
->freq("weekly")
->until($after10Weeks)
->byday(array('MO', 'WE', 'FR'))
->generateOccurrences();
$occurrences = $r->occurrences;
Use PHP DateTime ISO date:
$date = new DateTime(); //The object
$year=2015; // Desired year
$days = array('Mon', 'Wed', 'Fri'); // Desired days of week
for ($yearDay=1; $yearDay<=366; $yearDay++) {
$date->setISODate($year,null, $yearDay); // call ISO Date
$week=$date->format('W'); // Get the week resulted
$day=$date->format('D'); // Get the day name resulted
if($week==10 && in_array($day, $days)) // return only dates of desired days of week 10
echo $date->format('M d Y')."<br>";
}
More information about ISO Date here
You can try this code with PHPTester
So I've got a table display of a calendar. I need to use PHP to evalute each row and if the row is on a Saturday or Sunday then set to a specific CSS class that will highlight the row as red.
if (isset($_POST['date'])) {
//store passed data from date to variables
$startdate = date('Y-m-d', strtotime($_POST['date']));
$holdstart = $startdate;
$enddate = date('Y-m-t', strtotime($_POST['date']));
} else {
// Nothing passed use current month
$startdate = date('Y-m-d');
$holdstart = $startdate;
$enddate = date('Y-m-t');
};
The above is the PHP code I use in order to produce the table. The code below is the code used to loop through the days in the calendar that is selected:
//loops through each day of the month
while ($startdate != $enddate) {
$startdate = date('Y-m-d', strtotime($startdate . ' +1 day'));
$friendlymonth = date('D d M Y', strtotime($startdate));
$dates[] = $startdate;
}
I know that what I'm looking for is an if condition however I don't know how to exactly specify the date and evaluate a condition based on if the date is a Saturday or a Sunday. Thanks for reading.
date('N', $timestamp) will return numeric representation of the day of the week (1-7).
Found the solution:
<?php if(date('w', strtotime($startdate)) == 6 || date('w', strtotime($startdate)) == 0) { echo 'danger'; }?>
For anyone that doesn't know $startdate is the variable where my date is stored in. If you see there where I've evaluate the condition to the values 6 and 0. Its because 6 to PHP is Saturday, 0 is Sunday. And the it starts from 1 = Monday, ans so forth. Feel free to chime in if I've added anything wrong.
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;