CodeBlanks Logo Icon CodeBlanks

Summary - Date and time

PHP course · Intermediate · Lesson 110/115

Build an event calendar app with date, strtotime and DateTime.

Summary - Date and time

In this group you learned four ways to handle dates and times in PHP: formatting with date(), getting a timestamp with time(), parsing strings with strtotime() and object-oriented work with the DateTime class.

You also practised adding durations with DateInterval and walking ranges with DatePeriod. Together these tools let you build event calendars, reminders and reporting systems.

Now you will write a mini event calendar that brings it all together.

Exercise Event calendar: next event one week later

An event starts on 2024-06-10. Create an $event object with new DateTime('2024-06-10'). Add one week (7 days) with $event->add(new DateInterval('P7D')). Then print the next event date with echo $event->format('d.m.Y').

Show example solution
Create with $event = new DateTime('2024-06-10'); add $event->add(new DateInterval('P7D')); then write echo $event->format('d.m.Y');
Example solution:
<?php
date_default_timezone_set('UTC');

$event = new DateTime('2024-06-10');
$event->add(new DateInterval('P7D'));
echo $event->format('d.m.Y');

Test yourself

  1. Which line moves a DateTime object one month forward?

    • $date->add(new DateInterval('P1M'));
    • $date->modify('+1 day');
    • $date->format('P1M');
    • strtotime('+1 month', $date);
    Show answer

    $date->add(new DateInterval('P1M')); — Correct. add(new DateInterval('P1M')) moves it one month forward.

  2. Compute tomorrow with strtotime

    $tomorrow = date('Y-m-d', strtotime('____'));
    Show answer
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
  3. Match date tools

    date()
    Formatting
    time()
    Timestamp
    strtotime()
    String parsing
    DateTime
    Object-oriented
    DateInterval
    Adding durations

All lessons in Intermediate