Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert a string into a DateTime without overwriting it OR modify the string without having to convert it?

So I’m trying to make the code echo the date for the last saturday of february of the chosen year, but the method I attempted using completely overwrote the value of the string. I need the string to keep its value but still modify it into telling me the last saturday of february.

Heres the code:

´´´
<?php

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$valdatum = date ("y-m-d H:i T", 0);

if(isset($_POST["valdatum"])) {
    $valdatum=filter_input(INPUT_POST, 'valdatum', FILTER_SANITIZE_SPECIAL_CHARS);
}
?>
<!DOCTYPE html>
<html lang="sv">
    <head>
        <title>Tjejvasan</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form method="POST">
            <input type="date" name="valdatum" value="<?= $valdatum;?>">
            <input type="submit" value="Skicka">
        </form>
    <?php
    echo $valdatum;
    echo "<br>";
    $valdatum = new DateTime;
    $valdatum->modify('last saturday of february');
    $valdatum2 = $valdatum->format('Y-m-d');
    echo $valdatum2;
    ?>
    </body>
</html>

´´´

>Solution :

You seem to have tied yourself in a few knots. I think this is what you need, although your description is not 100% clear:

if(isset($_POST["valdatum"])) {
    //use the date value submitted from the form
    $valdatum = $_POST["valdatum"];
}
else
{
  //use today's date when nothing else was submitted
  $valdatum = date("y-m-d");
}
?>
<!DOCTYPE html>
<html lang="sv">
    <head>
        <title>Tjejvasan</title>
        <meta charset="utf-8">
    </head>
    <body>
        <form method="POST">
            <input type="date" name="valdatum" value="<?= $valdatum;?>">
            <input type="submit" value="Skicka">
        </form>
    <?php
    //change the date to the last saturday in February of the same year
    $febDate = new DateTime($valdatum);
    $febDate->modify('last saturday of february');
    echo $febDate->format('Y-m-d');
    echo "<br>";
    ?>
    </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading