1

I need to be able to add 7 date to an already formatted date.

I have a variable:

$holiday has a value of Wednesday 1st of January (for example);

I am tryng to add 7 days to this result so the output would be 8th of January but this fails, the code i use is as follows

if (strpos($holiday,'1st') && strpos($holiday,'January') == true) {$result = date("l jS \of F", strtotime( $holiday. "+ 7 day" ));}

No errors in php log

TJ15
  • 353
  • 2
  • 10
  • 22
  • `strpos()` is used like `strpos('mixed','needle')!==false` because postion = 0 will not match with `strpos('mixed','needle')==true` – JustOnUnderMillions Apr 07 '17 at 13:39
  • @JustOnUnderMillions So i should use !== false rather that == true in the above example? The check seems to be working but will try this out. Any idea about addng 7 days to a formatted date? – TJ15 Apr 07 '17 at 13:47
  • 2
    See the diffrence between `var_dump(strpos('abc','a')==true);` and `var_dump(strpos('abc','a')!==false);` Both should be `true`. Its all about how php type cast values in conditions. http://php.net/manual/en/types.comparisons.php You should alway use `strpos()!==false` – JustOnUnderMillions Apr 07 '17 at 13:53
  • Possible duplicate of [Adding days to $Date in PHP](http://stackoverflow.com/questions/3727615/adding-days-to-date-in-php) – Hamza Zafeer Apr 07 '17 at 13:58
  • 1
    @Hamza Zafeer Problem is, that this example is not an format that is supported by date function in php. – JustOnUnderMillions Apr 07 '17 at 13:59

2 Answers2

1

So if this examples Wednesday 1st of January is always the format.

Like [DAY] [DAYNUM] [of] [MONTH]

Then you can do:

 $date ='Wednesday 1st of January';
 $arr = explode(' ',$date);
 $arr[1]=(int)$arr[1];//we cast `1st` to int so it becomes `1`
 unset($arr[2],$arr[0]);//we ignore `of` and `DAY`
 $datenew = implode(' ',$arr);
 $d = DateTime::createFromFormat('j F',$datenew);
 print $d->format('Y-m-d');//2017-01-01
 print $d->modify('+7 days')->format('Y-m-d');//2017-01-08
JustOnUnderMillions
  • 3,741
  • 9
  • 12
0

As the alternative to strtotime you can use DateTime::createFromFormat.

Then you can use other date functions or just add 86400 * 7 seconds to the timestamp.

ghostprgmr
  • 488
  • 2
  • 11
  • If you choose to manually adjust a value with seconds (or minutes), be mindful of daylight savings transitions. – zenzelezz Apr 07 '17 at 14:04
  • 1
    Of course. I mentioned that variant only because it exists. [DateTime::add](http://php.net/manual/en/datetime.add.php) will be better. – ghostprgmr Apr 07 '17 at 14:41