Matt Picca
Matt Picca

Reputation: 142

PHP taking user input and formatting output (dates)

I'm new to php and need some help, I am trying to take the user input and format it so that the output shows the last day of the month. Here's what I have so far:

<?php
    //form for user-input
    echo "<form name='form' method='post' action='array.php'>";
    echo "<p>Enter Date in ' Month/Day/Year ' format<p>";
    echo "<input type='text' id='date-input' name='date-input' placeholder='Enter date' />";
    echo "</form>";

    //grab user-input
    $input=$_POST["date-input"];

    //output in correct format
    echo $input->format("m/t/Y");


?>

When I have just echo input variable without the format function and date format then it displays what the user inputs, but how it's set right now; nothing displays and I get this line:

Fatal error: Call to a member function format() on string in C:\xampp\htdocs\php-sessions\session-3\array.php on line 190

Line 190 is my echo input line.

Upvotes: 1

Views: 1886

Answers (3)

Soni Vimalkumar
Soni Vimalkumar

Reputation: 1462

Maybe Match your requirements,

<?php

$date = "2040-11-23";

$Year = DateTime::createFromFormat("Y-m-d", $date)->format("Y");

$YearWithDay = DateTime::createFromFormat("Y-m-d", $date)->format(" Y-m, t \d\a\y.");

function is_leap_year($year)
{
   return ((($year % 4) == 0) && ((($year % 100) != 0) || (($year % 400) == 0)));
}

echo $YearWithDay."<br>";
echo (is_leap_year($Year))?"This Year is Leap year": "";

?>

OUTPUT

2040-11, 30 day.
This Year is Leap year

Upvotes: 0

bansi
bansi

Reputation: 57002

Try this. You may need to create a date first from your input string. Used createFromFormat

$date = DateTime::createFromFormat('m/d/Y', $input);
echo $date->format('m/t/Y');

Note: Remember to use timezone parameter also with all datetime functions.

Upvotes: 2

Naga
Naga

Reputation: 2168

something like replace

//output in correct format
    echo $input->format("m/t/Y");

with

//output in correct format
    echo date("m/d/Y",strtotime($input));

Upvotes: 0

Related Questions