Given a day and month, return the most recent date of that day and month in the form day-month-year
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 t开发者_Python百科o "31 December, 2009").
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
}
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");
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;
?>
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
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.
精彩评论