0

So I'm just making a basic calendar for each month, just to play with the date function in PHP. I use something very simple code that I was thinking of throwing into a loop and populate some cells in a table:

public function getDayDate(){
    $month = "January";
    $day="1";
    $year="2014";
    $theW = "$month $day $year";
            //First day of the week on a month
    echo date("D", strtotime($theW));
            //# of days in a month
    echo date("t", strtotime($theW));
}

But it came to my mind about leap year and all other kinds of calendar events that may effect the number of days in a month. And i was wondering if this basic setup automatically factors these things in with the data here. Cause I figured I can have start on a particular cell like Wednesday and loop it 28-31 times to add the day to each cell until it completes.

Is this wrong? I tried searching for about a day, and most of the questions are more specific for finding the leap year and/or event, instead of it automatically just giving the end result, which is the number of days in the month and what day of the week it starts on.

I appreciate your help!

3
  • I suggest to use php DateTime object, I think date() function is deprecated. Jan 9, 2014 at 23:20
  • date knows about leap years, yes. I'd prefer a DateTime, DateInterval & DatePeriod combo for creating calendars, but that is just a personal preference.
    – Wrikken
    Jan 9, 2014 at 23:21
  • 3
    And date is NOT deprecated (and most likely never will, there's no reason), but DateTime has a LOT of advantages.
    – Wrikken
    Jan 9, 2014 at 23:22

2 Answers 2

3

Yes, PHP's DateTime class does. You can even check if it is a leap year with the L formatter.

$date = date_create();
$isLeapYear = $date->format('L');
var_dump($isLeapYear);
0

You can easily test it. Calculate the diff between Feb 27th and March 2nd for example in a leap year and in a non leap year and you will see that they are different.

I recommend you use DateTime::createFromFormat for transforming your string into a date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.