[RESOLVED] Date increment by month: seemingly odd results from strtotime
Hi everyone
When looping and incrementing dates, I noticed that one date was incrementing incorrectly. On checking the code I realised I'd done it a rather poor way and fixed it, but does
anyone know why I get the results shown?
Maybe you could use the "first day of next month" and/or "last day of next month" strotime() expressions, if that's what you ultimately want?
Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be." ~ from Nation, by Terry Pratchett
"But the main reason that any programmer learning any new language thinks the new language is SO much better than the old one is because he’s a better programmer now!" ~ http://www.oreillynet.com/ruby/blog/...ck_to_p_1.html
It's probably because you're using 't' in your date() function instead of something like 'd' or 'j'. I can't say for sure that's the issue but they are different and it's what stuck out to me immediately.
The best way of incrementing dates (or working with dates/times in general) in my opinion is using the DateTime class.
No comment on the OP's issue, you guys have offered plenty of pointers.
Interesting story, somewhat related ... yesterday I was updating a calendar routine I wrote last month to show "the previous month", and it showed that November 4th occurred twice. Had me scratching my head for a while until I realized that 4 Nov was the day after the US went back to Standard Time from Daylight Savings. I was doing something like "$ts+=86400" to loop through days; when the calendar added that extra hour ... [insert lightbulb moment here] ... problem now solved.
If there's a "moral" to this story, it's "use PHP built-in functions whenever possible"
/!!\ mysql_ is deprecated --- don't use it! Tell your hosting company you will switch if they don't upgrade!/!!!\ ereg() is deprecated --- don't use it!
dalecosp "God doesn't play dice." --- Einstein "Perl is hardly a paragon of beautiful syntax." --- Weedpacket
NogDog, I didn't know about the "first day of next month" and/or "last day of next month" strotime() expressions. I can't find a definitive list of strtotime options but I'm sure there's one somewhere. strtotime is amazing.
Bonesnap, thanks for the DateTime class which I didn't know about either. I do a lot of date manipulation so that'll help a lot.
Weedpacket, great point, I can see the consistency now that you point it out. Of course, strtotime doesn't know that adding one month to a date means I necessarily want the last day of the month; even if the current date 'happens' to be the last month day. I presume it just increments the month number and applies a date format to it; I guess that step increments the year and resets the month to 1 if required.
dalecosp and bradgradfelman demonstrate the point further very well; use PHP built-in functions to work with dates.
Bookmarks