Getting first and last day of the month
Earlier today I was working on this form with two textboxes which had to initially show the first and last day of the current month respectively.
So I wanted a compact way of doing this using PHP without using a function or method and show the date in format d/m/yyyy. The first day of the month is straight forward and I could have used something simple like this:
$dtFirstDay = "1/" . date("m") ."/" . date("Y") ;
This could have done it but in the end I settled for a method with similar formulations for both first day and last day and hence:
$dtFirstDay = date("j/n/Y", mktime(0, 0, 0, date("m") , date("d")-date("d")+1, date("Y")));
and for last day:
$dtLastDay = date("j/n/Y", mktime(0, 0, 0, date("m")+1 , date("d")-date("d"), date("Y")));
Thanks for the code snippets, exactly what I was looking for.
reply
Good to hear that the code snippets helped you Gary. Cheers.
reply
Nice. Saved me some time! One note: for the last-day-of-the-month calculation, you could just put 0 instead of date("d")-date("d") . This saves 2 calls to date().
reply
Thx Wes - this is really wonderful code snippet indeed. Thanks to you millions.
reply
Hi, a lot of PHP developers look for this so that code can be better.
The first day ever be "1";
$dtFirstDay = date("j/n/Y", mktime(0, 0, 0, date("m") , 1, date("Y")));
and for last day:
$dtLastDay = date("j/n/Y", mktime(0, 0, 0, date("m")+1 , 0, date("Y")));
This way we won't spend time to
"date("d")-date("d")";
reply
Thanks Francisco for your contribution, it think it will definitely help other Php developers.
reply
Thanks for the code, this is what i exactly wanted.
reply
Good to hear that you found this useful Santhosh.
reply
thank you, i'm searching and asking this scrip t in the forum and no one even bother to reply my question. no i found it in here.
(",)
thanks
reply
Thanks for the tips, I ended up using your code today. It works nicely, its really hard to find these random things when you need something really specific in mysql. Everyone has unique ways of handling mysql. Anyways, thanks for the code snippet.
reply
your script saved me precious time, thanks a lot
reply
Thanks for the post,exactly what I was looking for.
reply
Nice approach but, for the month you should use date("n") and for the day (if you don't want to remove it) date("j"). Otherwise you might end up with octal values as m & d contain leading zeros.
reply