Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get next week dates?

Tags:

php

Problem

I'm using the below code to get the next week's date and second week's date. It works fine for first few records but later it starts giving year 1970.

If the start date is 12/01/2013 it shows me coorect result that is:

Next week: 19/01/2013

Second week: 26/01/2013

but in another record where the date is 16/05/2013 it shows the below

Next week: 08/01/1970

Second week: 15/01/1970

Please guide me where I might be going wrong ?

Code

    //Date of when game started
    $starts_on = '12/01/2013';    

    //Next week's 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's 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;
like image 436
colourtheweb Avatar asked May 28 '13 13:05

colourtheweb


1 Answers

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

Dates in the m/d/y or d-m-y formats are disambiguated by looking at 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 dot (.), then the European d-m-y format is assumed.

Check the documentation further:

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

like image 90
Vedran Šego Avatar answered Oct 05 '22 22:10

Vedran Šego