tags:

views:

53

answers:

5

Given a date like "4 May", how do I get the most recent 4th May in the format "4 May, 2010"?

If the day/month combination has not yet occurred this year, it should show the date for last year (e.g. "31 December" should translate to "31 December, 2009").

+1  A: 

Try something like this:

$cmpDate = strtotime('March 15');
$cmpDay = date('d',$cmpDate);
$cmpMonth = date('m',$cmpDate);

$currentDay = date('d');
$currentMonth = date('m');

if(($currentDay > $cmpDay && $currentMonth == $cmpMonth) || ($cmpMonth > $currentMonth) {
 // Add one year
}
Prot0
A: 

Try this (this is psuedo-code):

<?php
    $currMonth = (int)date("m");
    $currentDate = (int)date("d");
    $currentYear = (int)date("Y");

    // extract date and month from given date as needed,
    // call it $givenMonth, $givenDate

    if (($givenMonth <=  $currMonth) && ($givenDate <= $givenDate)) {
        $givenYear = $currentYear;
    }
    else {
        $givenYear = $currYear - 1;
    }

    echo "Given date is: " + $currentMonth + "/" + $currentDate + "/" + $currentYear;
?>
Wade
A: 
function recentizer($date) {
    $year = date('Y', time());

    return (strtotime($date) < time()) ?
            $date . ' ' . $year : $date . ' ' . ($year-1);
}

Example:

$dates = array('4 May', '6 February', '23 December');

foreach ($dates as $date) {
    echo recentizer($date) . "\n";
}

Outputs:

4 May 2010
6 February 2010
23 December 2009
NullUserException
Not entirely accurate, as the date of today (Example 'August 11') would be translated to August 11, 2010 0:00:00 which will in most occasions be less than time()
Prot0
@Prot Shouldn't it be? IDK. That's up to the OP to tweak.
NullUserException
Just saying, since the question states "If the day/month combination has not yet occurred this year," :-)
Prot0
+1  A: 

my tip is to use date('z') (= day of the year) for comparisons

$date = '11 Aug';
$ts = strtotime($date); 
$recent = date('z', $ts) <= date('z') ? $ts : strtotime("$date previous year");
stereofrog
A: 

You can use this function:

echo date('m/d/y',strtotime('5 Sep',strtotime('-1 year'.str_repeat(' +1 year',(time()-strtotime('5 Sep'))/abs(time()-strtotime('5 Sep')) ) )) );

and change '5 Sep' to whatever date you want.

It works by setting the base year in strtotime to the current prior year (ie, '-1 year'), and then adjusts back to the current year (ie '+1 year') if the current time is greater than the time provided in your string.

KMW