Reputation: 767
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;
Upvotes: 6
Views: 3329
Reputation: 499
Please try this
$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);
Upvotes: 0
Reputation: 5230
I recommend you use the DateTime Object, is better to manipulate dates (to add and substract dates from another is very easy with the object DateInterval)
<?php
$date = new DateTime("2013-01-12");
//add one week to date
echo $date->add(new DateInterval('P1W'))->format('Y-m-d');
//add one week to date
echo $date->add(new DateInterval('P1W'))->format('Y-m-d');
?>
Result:
2013-01-19
2013-01-26
References:
http://php.net/manual/es/class.datetime.php
http://php.net/manual/es/class.dateinterval.php
Upvotes: 4
Reputation: 3765
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()
andDateTime::sub()
in PHP 5.3 and later, orDateTime::modify()
in PHP 5.2.
Upvotes: 5