Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 36 / 68

Building and Displaying Dates (Basic Year/Month/Day Operations)

In this lesson you will learn the basics of working with dates through PHP's DateTime class, so you can build and display a date and its day of the week correctly. This is for anyone searching for "PHP DateTime how to use".

The DateTime class lets you assemble and work with a specific date. Reading the day of the week and changing the display format are both straightforward. It is unavoidable background knowledge for any date-driven application, from booking systems to event calendars.

The sample code creates a date object with new DateTime("2026-08-09") and formats it readably with $date->format("n/j/Y"). The weekday number from $date->format("w") is then looked up in an array of names.

A common stumbling block for beginners is what the format characters mean. Y is the four-digit year, n the month without a leading zero, j the day without a leading zero, and w the weekday number - you pick them up gradually.

Combined with the modify() method you can easily calculate differences in days, months, or years. Working out a membership expiry or an event deadline is a routine requirement in real systems.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)