Envious
Envious

Reputation: 487

strtotime using date input

Right now I have a form that contains an HTML5 date input, and second hidden input that uses strtotime to get todays weekday (mon, tue etc). The problem is if someone selects 12/5 today, it will input into the database 12/5 and Friday when it really should be 12/5 Wednesday.

<input class="form" id="date" type="date" name="date" size="15" placeholder="yyyy-mm-dd" autofocus required />

<input type="hidden" name="weekday" value="<?php echo date('l',strtotime('now')); ?>" />

When I implemented it, I didn't think using today's date would be an issue. But the use case has changed, and people inputting new results, but using older dates will be mismatched. It would show up as 12/5 in the date and Friday in the weekday when it should be Wednesday.

I'm not sure how to link the two input's together since the form hasn't actually been submit yet. Any help would be appreciated.

Upvotes: 1

Views: 2128

Answers (2)

Michael Irigoyen
Michael Irigoyen

Reputation: 22957

Just use PHP's DateTime functions and remove the hidden field all together.

$date = date_create($_POST['date']);
$day = $date->format('l');

More information on the DateTime construct: https://www.php.net/manual/en/datetime.construct.php

I highly recommend getting into the habit of using the DateTime class built in to PHP over the traditional date functions. They're typically easier to work with and are not affected by the unix epoch limitations. They can also be used in Object Oriented fashion or in procedural, depending on your coding preference.

Upvotes: 1

Liftoff
Liftoff

Reputation: 25412

Why don't you just do this on the server side?

$date = $_POST["date"];
$dateString = date('m/d l',strtotime($date));

Read more about PHP date()

Read more about PHP strtotime()

Just remove the hidden input altogether. It is not necessary.

Upvotes: 1

Related Questions