PHP Date and Time

Certainly! PHP provides a range of functions to work with dates and times. Here's an overview of some commonly used date and time functions in PHP:


1. Current Date and Time:

php
$currentDate = date("Y-m-d"); // Current date in YYYY-MM-DD format
$currentTime = date("H:i:s"); // Current time in HH:MM:SS format

2. Formatted Date:

php
$formattedDate = date("F j, Y, g:i a"); // Example: August 7, 2023, 2:30 pm

3. Unix Timestamp:

php
$timestamp = time(); // Current Unix timestamp

4. Custom Date and Time:

php
$customDateTime = date("Y-m-d H:i:s", strtotime("2023-08-07 14:30:00"));

5.Date Arithmetic:

php
$futureDate = date("Y-m-d", strtotime("+1 week")); // Current date + 1 week
$pastDate = date("Y-m-d", strtotime("-2 days")); // Current date - 2 days

6. Formatting a Unix Timestamp:

php
$timestamp = 1628346000; // Example timestamp
$formattedTimestamp = date("F j, Y, g:i a", $timestamp);

7. Timezone Handling:

php
date_default_timezone_set("America/New_York"); // Set timezone
$formattedDateNY = date("F j, Y, g:i a");

8. Date Diff:

php
$date1 = new DateTime("2023-08-01");
$date2 = new DateTime("2023-08-07");
$interval = $date1->diff($date2);
echo $interval->format("%R%a days"); // +6 days

9. Get Day of Week:

php
$dayOfWeek = date("l"); // Example: Monday

10. Get Month and Year:

php
$month = date("F"); // Example: August
$year = date("Y"); // Example: 2023

These are just a few examples of how you can work with dates and times in PHP. PHP's date and time functions are versatile and can be combined to suit various requirements for formatting, manipulation, and calculations involving dates and times. Remember to refer to the PHP documentation for more details on each function and their options: [PHP Date and Time Functions]( https://www.php.net/manual/en/ref.datetime.php ).


e.g-

<!DOCTYPE html>
<html>
    <body>

        <?php
        echo "Today is " . date("Y/m/d") . "<br>";
        echo "Today is " . date("Y.m.d") . "<br>";
        echo "Today is " . date("Y-m-d") . "<br>";
        echo "Today is " . date("l");
        ?>
    </body>
</html>

OUTPUT-

Today is 2023/08/07
Today is 2023.08.07
Today is 2023-08-07
Today is Monday



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext