WikiGalaxy

Personalize

PHP Date and Time

Displaying Current Date and Time:

To display the current date and time in PHP, you can use the date() function. This function formats a local date and time, and returns it as a string.


<?php
echo date('Y-m-d H:i:s');
?>
        

Console Output:

2023-10-05 14:30:00

PHP Date and Time

Formatting Date:

The date() function can also be used to format dates in various ways, such as displaying only the year, month, or day.


<?php
echo date('l, F j, Y');
?>
        

Console Output:

Thursday, October 5, 2023

PHP Date and Time

Timestamp:

A timestamp in PHP is the number of seconds since January 1, 1970. You can get the current timestamp using the time() function.


<?php
echo time();
?>
        

Console Output:

1696523400

PHP Date and Time

Converting a Timestamp to a Date:

You can convert a timestamp to a more readable date format using the date() function.


<?php
$timestamp = 1696523400;
echo date('Y-m-d H:i:s', $timestamp);
?>
        

Console Output:

2023-10-05 14:30:00

PHP Date and Time

Using strtotime() Function:

The strtotime() function parses an English textual datetime description into a Unix timestamp.


<?php
$timestamp = strtotime('next Monday');
echo date('Y-m-d H:i:s', $timestamp);
?>
        

Console Output:

2023-10-09 00:00:00

PHP Date and Time

Calculating Date Differences:

You can calculate the difference between two dates using the diff() method of the DateTime class.


<?php
$date1 = new DateTime('2023-10-05');
$date2 = new DateTime('2023-12-25');
$interval = $date1->diff($date2);
echo $interval->format('%R%a days');
?>
        

Console Output:

+81 days

PHP Date and Time

Adding and Subtracting Dates:

You can add or subtract dates using the modify() method of the DateTime class.


<?php
$date = new DateTime('2023-10-05');
$date->modify('+1 month');
echo $date->format('Y-m-d');
?>
        

Console Output:

2023-11-05

PHP Date and Time

Time Zones:

In PHP, you can set the default timezone using the date_default_timezone_set() function.


<?php
date_default_timezone_set('America/New_York');
echo date('Y-m-d H:i:s');
?>
        

Console Output:

2023-10-05 10:30:00

PHP Date and Time

Creating Custom Date Formats:

You can create custom date formats using the date_format() function with a DateTime object.


<?php
$date = new DateTime('2023-10-05');
echo $date->format('l, d F Y');
?>
        

Console Output:

Thursday, 05 October 2023

PHP Date and Time

Handling Leap Years:

PHP can easily handle leap years when calculating dates. You can check if a year is a leap year by creating a date and formatting it.


<?php
$year = 2024;
$date = new DateTime("$year-02-29");
echo $date->format('Y-m-d');
?>
        

Console Output:

2024-02-29

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025