Home > Blockchain >  Show a date depending on day and time
Show a date depending on day and time

Time:11-25

I have this script that echo's the upcoming Thursday, unless it's Wednesday because then it shows the Thursday a week later. This works great.

But what I would like is to add a cut-off time on Wednesday on 5PM (17:00 GMT 1 / CEST). So before 5PM it will still show the next Thursday (day after) but after 5PM it should be showing next week Thursday. I just can't seem to figure out how to add this, hopefully someone knows the solution!

<?
$date = new DateTime();
if(date('D') == 'Tue' || date('D') == 'Wed') {
$date->modify('thursday next week');
} else {
$date->modify('next thursday');
}
$delivery_date = $date->format('d-m-Y');
?>

<?php echo $delivery_date; ?>

CodePudding user response:

Some feedback for you:

  • your question states "unless it's Wednesday", but your code says unless it's Tuesday or Wednesday
  • You create $date with DateTime() which is great, but you are not using it in your if statement. Each of your date('D') calls in the if statement uses a separate time. The times will be very close, but you should use the $date that you created when checking the day, e.g. $date->format('D') === 'Wed'
  • Your code will work based on the server's time zone. If you need to deal with other time zones, you will need to specify that by passing a DateTimeZone object to your DateTime contructor, e.g. $date = new DateTime( 'now', $dateTimeZoneObj );, or manually setting the timezone before your code.

One way to address your issue is to add a 5pm check onto your day-of-the-week check, e.g.: if( $date->format('D') === 'Wed' && (int)$date->format('G') >= 17 )

  • Related