How to Add Seconds, Minutes, Hours, Days, Months and Years to a Date in PHP

June 17, 2020
PHP
add date and time in php

In this tutorial, I’m going to show you how to add several seconds, minutes, hours, days, months or years using PHP. This tutorial will not give you a good design but will provide you with an idea on the topic. Also, If you wanted to convert our output date, you may do so by visiting my previous tutorial about Converting Date Formats.

Creating Form and Output Date

We determine our output date by user input upon submission. We name this form as “index.php”.

<!DOCTYPE html>
<html>
<head>
<title>How to Add Seconds, Minutes, Hours, Days, Months and Years to a Date and Time in PHP</title>
<body>
    <h2>Our Date and Time: 2017-08-28 13:05:05</h2>
    <?php
        $olddate="2017-08-28 13:05:05";
        $newdate="";
    ?>
    <form method="POST">
        <input type="text" name="number">
        <select name="what">
            <option value="seconds">Seconds</option>
            <option value="minutes">Minutes</option>
            <option value="hours">Hours</option>
            <option value="days">Days</option>
            <option value="months">Months</option>
            <option value="years">Years</option>
        </select>
        <input type="submit" name="add" value="Add">
    </form>
    <?php
        if (isset($_POST['add'])){
 
            $number=$_POST['number'];
            $what=$_POST['what'];
 
            echo "<br> You have added ".$number." ".$what.".";
            $newdate=date('Y-m-d H:i:s', strtotime("+$number $what", strtotime($olddate)));
 
        }
 
    ?>
    <h2>New Date and Time: <?php echo $newdate; ?> </h2>
</body>
</head>
</html>

Happy Coding!

Download Code

Leave a Reply

Your email address will not be published. Required fields are marked *