views:

513

answers:

2

I'd like to get an 'end date' from a given 'start date' in PHP. End date is based off the start and are calculated as follows:

If Start date is from the 1-15th of the month, End date is the 15th of the following month.

If Start date is from the 16-31 of the month, End date is the last day of the following month.

eg: $start_date = '2009-11-23';

+1  A: 

could this work?

$start_timestamp = strtotime('2009-11-17');
$d1 = getdate($start_timestamp);

$end_timestamp = mktime(
    0,
    0,
    0,
    $d1['mon'] + 1 + floor($d1['mday']/16),   // 1 before the 16th, then 2
    15 * (1-floor($d1['mday']/16)),        //15 before the 16th, then 0
    $d1['year']
);
$end_date = date('Y-m-d', $end_timestamp);
goorj
I'm getting Notice: A non well formed numeric value encountered indate.php on first line
Mithun P
sorry, my code worked with timestamps. Changed and tested it.
goorj
Small correction, Fourth argument to the mktime function should be $d1['mon'] + 1 + floor($d1['mday']/16) and not $d1['month'] + 1 + floor($d1['mday']/16), the later will alwyas generate 01 in the moth part
Mithun P
You're right, again being sloppy, sorry! Changed it.
goorj
+1  A: 

Here's another way to do it:

$dt = new DateTime($start_date);
if ($dt->format('d') > 15) {
    $day = 'last day';
} else {
    $day = (15 - $dt->format('d')) . ' days';
}
echo $dt->modify('next month ' . $day)->format('Y-m-d');
GZipp