1

I'm wondering if there's an easy way (like using strtotime) whereby I can get the unix time for the last occurrence of a day/month combination. For example, if I was to ask for "1st of September" today (9th May 2012) I would get 1314835200 (1st Sep 2011), but if the code was to run again this October, I would get 1346457600 (1st Sep 2012), and the same if I ran it 1 year from now.

Being able to do it forwards as well as backwards would be a massive bonus.

marxjohnson
  • 830
  • 7
  • 21
  • 1
    I'd recommend having a search, http://stackoverflow.com/search?q=%5Bphp%5D+last+day+of+the+month There are quite a few examples. **Top tip** In the search if you put your chosen tags in [php] then you can restrict search to just that tag :) – David Yell May 09 '12 at 12:34
  • @DavidYell You might want to re-read the question – jprofitt May 09 '12 at 12:44
  • possible duplicate of http://stackoverflow.com/search?q=get+next+occurence+of+a+date+php&submit=search – Gordon May 09 '12 at 12:49
  • Duplicate of http://stackoverflow.com/q/7699529/212940 – vascowhite May 09 '12 at 12:52
  • 4
    Thanks for your comments, I did a search (as you know, Stackoverflow even searches for you before you post), but didn't find an answer to my question, hence my posting. I don't believe that any of the links posted are, in fact, the same question. – marxjohnson May 09 '12 at 12:58

1 Answers1

7
$month = 9;
$day = 1;

$timestamp = mktime(0, 0, 0, $month, $day);
if ($timestamp > time()) {
    $timestamp = mktime(0, 0, 0, $month, $day, date('Y') - 1);
}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • This certainly does the job. It can also look forwards (i.e. return the next 1st of September) by changing the > to < and - to +. Unless someone amazes me with a 1-liner (I suspect there isn't one, save for ternary operators) I'll go with this answer. – marxjohnson May 09 '12 at 12:47
  • why do you answer duplicates? – Gordon May 09 '12 at 12:48
  • 2
    @Gordon Because it was easier than finding an appropriate dupe. Don't tell me somebody downvoted me for that? – deceze May 09 '12 at 12:57
  • 1
    @deceze of course they did. Repwhoring is discouraged, unfair and contributing to making finding suitable dupes harder. See http://meta.stackexchange.com/a/105231/168606. – Gordon May 09 '12 at 13:03
  • 5
    @Gordon Oh great, as if I need to rep whore. Terribly sorry if I have offended anyone by helping the OP out... -_-# BTW, I did not see you finding a perfect duplicate either... – deceze May 09 '12 at 13:05
  • @deceze true, I nowadays close most date related questions as too localized because I cannot be bothered anymore to wade through the thousands of answers that say use `mktime`, `date`, `strtotime` or `datetime`, which should give any OP enough pointers to solve questions like this on their own. – Gordon May 09 '12 at 17:14