How can I get dates next week?

Problem

I use the code below to get the next date of the week and second week. It works great for the first recordings, but the year 1970 later begins.

If the start date is 12/01/2013 , this shows me the result of coorect, which:

Next week: 01/19/2013

Second week: 01/26/2013

but in another entry where the date 05/16/2013 is displayed below

Next Week: 08/01/1970

Second week: 15/01/1970

Please tell me where can I make a mistake?

code

//Date of when game started $starts_on = '12/01/2013'; //Next week date from start date $next_week = strtotime(date("d/m/Y", strtotime($starts_on)) . "+1 week"); $next_week = date('d/m/Y', $next_week); //Second week date from start date $second_week = strtotime(date("d/m/Y", strtotime($starts_on)) . "+2 week"); $second_week = date('d/m/Y', $second_week); echo $starts_on.", ".$next_week.", ".$second_week; 
+6
source share
3 answers

You are using the wrong format date. Check the note in the strtotime documentation :

Dates in m / d / y or dmy formats are resolved ambiguously by considering the separator between the various components: if the separator is a slash (/), then the American m / d / y is assumed; whereas if the separator is a dash (-) or a period (.), then the European dmy format is assumed.

Check the documentation further:

Using this function for mathematical operations is impractical. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

+5
source

I recommend using a DateTime object, it is better to manipulate dates (adding and writing dates from another is very easy using the DateInterval object)

 <?php $date = new DateTime("2013-01-12"); //add one week to date echo $date->add(new DateInterval('P1W'))->format('Ym-d'); //add one week to date echo $date->add(new DateInterval('P1W'))->format('Ym-d'); ?> 

Result:

 2013-01-19 2013-01-26 

Literature:

http://php.net/manual/es/class.datetime.php

http://php.net/manual/es/class.dateinterval.php

+4
source

Please, try

 $dt = new DateTime(); // create DateTime object with current time $dt->setISODate($dt->format('o'), $dt->format('W')+1); // set object to Monday on next week $periods = new DatePeriod($dt, new DateInterval('P1D'), 6); // get all 1day periods from Monday to +6 days $days = iterator_to_array($periods); // convert DatePeriod object to array echo "<pre>"; print_r($days); 
0
source

Source: https://habr.com/ru/post/946015/


All Articles