Assume that I'm adding the date / time into a mysql database and have the following (small for once) chunk of code.
<input type="text" name="date">Leave time null for current<br />
<input type="Submit" name="submit" value="submit">
The Following is the form that catches that
$radate=$_POST['date'];
if ($radate=="")
$radate = date('Y-m-d H:i:s');
else {}
I've tried entering "2011-08-14 19:15:25" and it has returned all 0's, can someone help me out with this? Thanks a ton!
You would probably be better off using strtotime() to validate the date/time submitted, if it's a freeform date entry field especially. Otherwise, someone may miss-enter a date/time and unexpectedly have it use the current date/time instead.
$radate_valid = false;
$radate = $_POST['date'];
if (!$radate)
$radate = date('Y-m-d H:i:s');
if (strtotime($radate) === false)
$radate_valid = false;
else
$radate_valid = true;
// Somewhere else
if ($radate_valid !== true)
/* Do something to warn the user. */
http://codepad.org/x2eZay0Q
If you used dropdowns, and the time was not a factor, you could also use checkdate(), although from your example it looks like you do need the time.
However, what you have posted should work. Here is an example using your date you provided:
http://codepad.org/BK1yqyMT
(And here without fixing the if block: http://codepad.org/p3CfmOJK)
Related
I need to change the pattern of the input date field to Day.Month.Year, is it possible?
<input type="date" name="datum" value="datum"/>
Currently it looks like this:
but if I submit the form and catch the value in PHP then the value is stored like this "2022-02-17"
I found this section in the firefox documentation, but it does not provide any example.
You could correct the date once you catch the value with your PHP handler.
$date = $_POST['datum'];
$date = date("Y-m-d",strtotime($date));
To show date in d.m.Y format in HTML page, again convert it into
$date = date("d.m.Y",strtotime($date));
Here is an input form which passes date type to intermediate.php from a form.
<form action="intermediate.php" method="post">
<input type="date" name="vazhipadudate1" />
</form>
How can i get the picked date i tried this code snippet .It echos as 1970-01-01
Php code snippet.
$date='vazhipadudate1';
$time = strtotime($_POST["$date"]);
$storecart[$i]['date'] = date('Y-m-d', $time);
echo "Selected Date is..........".$storecart[$i]['date'] ;
The output i am getting as
Selected Date is..........1970-01-01
After reproducing the problem,
I think the problem is probably because your submitting the form without passing any value to input.
As The input has no def value. So it, POSTs empty string.
And when you pass the empty string to strtotime that returns false
Amd, again when you pass it to date that returns 1970-01-01 as (int) FALSE -> 0
So you should test the POST before processing it. Something like this to check POSTed data,
!empty( $_POST["vazhipadudate1"] )
# AND/OR,
$time = strtotime($_POST["$date"]);
if (time === false) /*TakeAppropriateAction*/;
I want to always show the previous third in the input and for this I do it this way:
$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = date($dia->format('d-m-Y'));
Then I want to show the variable $terca in the value of an input type date, but it does not show, only if it is datetime:
<td style="float:center"> <input type="date" name= "data" value="<?php echo $terca?>"></td>
Whenever I run the page I get this warning:
The specified value "19-02-2019" does not conform to the required
format, "yyyy-MM-dd".
I'm trying in this way date ('yyyy-MM-dd', strtotime ($terca)); but I still have the same problem
Change format('d-m-Y') to format('Y-m-d')
$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = date($dia->format('Y-m-d'));
Then try :
<input type="date" name= "data" value="<?php echo $terca?>">
The error-message tells you the problem right away:
The specified value "19-02-2019" does not conform to the required format, "yyyy-MM-dd"
Just change the format (put Y to the front):
$terca = date($dia->format('Y-m-d'));
Should solve your problem.
The error message is telling you that the string you've output into the value of the input box is not valid.
As is documented, the value of a "date" input must always be specified in yyyy-mm-dd format. This is irrespective of the format in which is it displayed to the user (which is chosen based on the user's browser locale settings).
You can fix it by using the correct PHP date format string, like this:
PHP:
$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = $dia->format('Y-m-d');
<input type="date" name="data" value="<?php echo $terca?>">
Runnable demo of PHP: http://sandbox.onlinephpfunctions.com/code/7045183fd11b5a2e29d5d9fa80f0910cad18d671
Runnable demo of HTML using the string output by the PHP: https://jsfiddle.net/0mqokve6/
P.S. since $dia is already a DateTime object, and format() already outputs a string, wrapping it in the date() function is redundant.
P.P.S. The reason the date control doesn't allow strings in other formats there is always a potential for ambiguity. e.g. dd-mm-yyyy can be impossible to distinguish from mm-dd-yyyy in many cases, such as 01-03-2019 as just one example. In that scenario it's impossible for the browser to know what the intended date was. yyyy-mm-dd is unambiguous and therefore always used to convey the actual value. The user can then be shown it in the format they're more culturally familiar with.
I have a form on a php page that submits information about events. Information submitted is stored in a MySQL database.
When a user does not select a date from the date picker, 0000-00-00 is inserted into the database. The column is set to default to null, leading me to think that this behavior is caused by the datepicker.
Can anyone suggest a way to allow insertion of a null value?
NOTE - I'm using the default html datepicker, not the jqueryUI version.
EDIT - on closer inspection its because the datatype in the database is a date, nothing to do with the datepicker.
form
<form action="add_event.php" method="post">
<div class="textWrap">
<label for="dateEndInput" id="title3">End Date</label>
<input id="dateEndInput" name="dateEndInput" type="text" value="" tabindex="3">
</div>
<input name="submit" type="submit" value="Submit" />
</form>
Thanks in advance
How about having an additional PHP statement before you do your SQL transaction that checks specifically for that value and var type and then setting it to null if it matches those conditions?
if ($date && $date === '0000-00-00') {
$date = null;
}
Alternatively, there's an inbuilt date_parse function
$date = '0000-00-00';
$parse_date = date_parse($date);
if ($parse_date['error_count'] > 0) {
$date = null;
}
However, there's also a DB side solution where you can change the column to not accept 0000-00-00 as a date. See http://dev.mysql.com/doc/refman/5.1/en/sql-mode.html#sqlmode_no_zero_date
This is going to be a bit difficult to explain but I will try my best to explain it as good as i can.
I am passing Data from an input textfield on one page (page1.php) to a Select form on another page (page2.php).
This works as should.
the Select Form contains some PHP timezones and when a timezone is selected, the page page will echo the current time for that timezone.
This also works as it should.
The problem is when I enter a timezone name in the input textfield on (page1.php) , it will show the name in the Select Form on (page2.php) BUT it will not echo its current time and it will throw out this error:
Fatal error: Uncaught exception 'Exception' with message 'DateTimeZone::__construct(): Unknown or bad timezone (London)' in page2.php:16 Stack trace: #0 on line 16.
when infact the timezone London exists in the Select Form Options and if I enter/search for London directly in the select form, it will echo the current time for that timezone but it will NOT if the timezone name was entered in the input textfield on page1.php and it was passed to the select form on page2.php!
here is what I have on page2.php:
<?php
if( isset($_POST['submit']))
{
//be sure to validate and clean your variables
$timezone2 = htmlentities($_POST['timezone2']);
//then you can use them in a PHP function.
function get_timezone_offset( $remote_tz ) {
$timezone2 = new DateTimeZone ( $remote_tz ); ----->>> Line 16 is here.
$datetime2 = new DateTime ("now", $timezone2);
$offset = $timezone2->getOffset($datetime2);
return $offset;
}
$offset = get_timezone_offset($timezone2);
}
?>
<?php
$options = array();
$options[$_POST["location"]] = $_POST["location"]; <<<<<<----- Data from input textfield on page1.php
$options["Africa/Addis_Ababa"] = "Addis Ababa"; <<<<<<----- Select Form Options
$options["Europe/London"] = "London"; <<<<<<----- Select Form Options
?>
and here is the Select Form on page2.php
<form id="myForm" name="myForm" class="myForm" method="post" action="page2.php">
<select style="font-size:9px;" name="timezone2" id="timezone2" class="timezone2">
<?php
foreach($options as $key => $value)
{
echo '<option value="'. $key .'" label="'. $value .'">'.$value.'</option>';
}
?>
<option value="<?php echo $_POST["location"]; ?>"><?php echo $_POST["location"]; ?></option>
</select>
</div>
<div id="myBtn" style="position:relative; float:left; width: 228px; margin-top:50px; margin-left:350px;"><input type="submit" name="submit" id="submit" class="submit" value="Search"/></div>
</form>
and here is the input textfield on page1.php
<form method="post" action="../page2.php">
<input name="location" type="text" value="Search"/>
<button type="submit">Search</button>
</form>
could someone please point me in the right direction?
You're going about this wrong for a few reasons. Firstly, the list of possible timezones is finite so get rid of the text field and just use a dropdown.
Second, you can remove\rename the items in the dropdown all you want but just remember that since you are saving the offset and not the tz name you can never go back (my example will show you exactly why that is if you play with it). Usually, it is best to store the name and not the offset so that you can manage daylight savings properly. You'll notice that to get this system to work I need to call date('I') to find out if it is daylight savings which is really bad (just because it's daylight saving in my server TZ doesn't mean it is in the users TZ). If you saved the TZ name instead you could defer that logic to PHP and just use whatever offset it currently is. This may not seem important in this simplistic example but if you ever tried to store that offset or calculate future\past times using it you'll definitely have troubles.
One other tiny thing is that it is odd to put function definitions inside of 'if' statements. In PHP all function definitions are global so it will be available regardless of whether the 'if' condition is true. The problem with doing that is now you've obscured your logic with no gain. It is easier and clearer to put that elsewhere.
I've rewritten your code to be a little nicer and to actually work as you are using it but I've left out a few details (like aliasing the TZ names [which you seem to have a handle on how to do] and switching to using TZ names instead of offsets [because that may break other code you have]) but I encourage you to fix those as well.
<?php
$tz_offset=0;
function get_offset_time($offset=0) {
$original=new DateTime("now");
$timezoneName=timezone_name_from_abbr("", $offset, date('I'));
if(!$timezoneName) die('ERROR: Unknown timezone \''.($offset/3600).'\'');
$oTZ=new DateTimezone($timezoneName);
$modified = $original->setTimezone($oTZ);
return $modified->format('Y-m-d H:i:s');
}
function get_timezone_offset($tz_name=null) {
if(!$tz_name) return 0; // If we have invalid data then return before we error
$tz=new DateTimeZone($tz_name);
$dt=new DateTime("now", $tz);
return $tz->getOffset($dt);
}
function enumerate_tz($tz_select=null) {
global $tz_offset;
$tz_ident=DateTimeZone::listIdentifiers();
foreach($tz_ident as $val) {
$tmp_offset=get_timezone_offset($val);
if($val=='UTC'||$tmp_offset)
echo '<option value="'.$val.'" '. ($tmp_offset==$tz_offset?' selected':''). '>'.
$val. ' [ '.($tmp_offset/3600).' ]'. // If you'd like to customize the viewable names for each TZ you may do so here
'</option>';
}
}
if(isset($_POST['tz_input']) && $_POST['tz_input']) {
$tz_input=htmlentities($_POST['tz_input']);
$tz_offset=get_timezone_offset($tz_input);
}
echo '<html><title>Timezone Select</title><body>'.
'<p>The current timezone offset is: '. ($tz_offset? ($tz_offset/3600): '0'). '</p>';
echo '<p>The current time is: '. get_offset_time($tz_offset). '</p>';
echo '<form method=post><select name=tz_input>';
enumerate_tz($tz_offset); // You'll notice that this list duplicates many of the timezones so that after selecting one the next
// time through it'll often select a different one. If you want to fix that you'll need to save the actually offset name instead of an offset.
echo '</select><input type=submit value=Search />'.
'</form></body>';
?>
EDIT: One other thing to note is that PHP's timezone_name_from_abbr() function is not complete. Some timezone offsets will not return a TimeZone name. You must account for that as well. For example, even though PHP understands the 'Pacific/Midway' timezone it cannot find it when doing a reverse lookup. I've updated the code so that won't cause a hard error anymore.
EDIT2: I can see that you aren't going to be happy until someone shows you how to shine that turd. Here you go:
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities($val);
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
Add this to your code and replace the call to htmlentities with a call to this:
$timezone2 = getOptionDX($_POST['timezone2'], $options);
Lastly, change this line:
if($timezone2) $offset = get_timezone_offset($timezone2);
If the user enters the TZ manually and it is correct then skip page2.php. This is as close to an answer as can be given if you don't want to change anything. The fact is that your logic is flawed in the first place (that is not meant to be a jab but it is true).
EDIT3: IDK what was wrong but here is my full code listing with the fixes you asked for:
<?php
$offset=0; $timezone2='';
$options = array();
$options["Africa/Addis_Ababa"] = "Addis Ababa";
$options["Europe/London"] = "London";
$options["America/Chicago"] = "The Windy City";
function getOptionDX($val, $option_array) {
if(!isset($option_array)||!is_array($option_array)||!count($option_array)>0||!$val) return null;
$val=htmlentities(ucwords(strtolower($val)));
if(isset($option_array[$val])) return $val;
$new_val=array_search($val, $option_array);
return $new_val!==FALSE?$new_val: null;
}
function get_timezone_offset( $remote_tz ) {
$timezone2=new DateTimeZone($remote_tz);
$datetime2=new DateTime("now", $timezone2);
$offset=$timezone2->getOffset($datetime2);
return $offset;
}
if(isset($_POST['location'])) {
$addLoc=getOptionDX($_POST['location'], $options);
if(isset($addLoc)) $options[$addLoc]=$_POST['location'];
else header('Location: '. $_SERVER['SCRIPT_NAME']);
}
if(isset($_POST['timezone2'])) {
$timezone2=htmlentities($_POST['timezone2']);
$offset=get_timezone_offset($timezone2);
}
if(isset($_GET['page2'])) {
?>
<form method=post action=?page2>
<select name=timezone2>
<?php foreach($options as $key=>$value) echo "\t".'<option value="'. $key .'"'.(get_timezone_offset($key)==$offset?' selected':'').'>'.$value.'</option>'."\n"; ?>
</select>
<input type=hidden name=location type="text" value="<?php echo $_POST['location']; ?>"/>
</div>
<input type=submit value=Search>
</form>
<p>Current Offset: <?php echo $offset/3600; ?></p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s'); ?> UTC</p>
<p>Current Time: <?php echo gmdate('Y-m-d H:i:s', time()+$offset).' '. $timezone2; ?> </p>
<?php
} else {
?>
<form method=post action=?page2>
<input name=location type=text value=""/>
<button type=submit>Search</button>
</form>
<?php
}
?>
I've tested this and know it works, if that isn't enough to answer your question then I give up. I'm starting to think that you really want a way to invent new timezones which don't exist. That isn't possible. You can alias those which already exists as I've done here which is as close as you're ever going to get. Logically, time zones can only range from -12:00 to +12:00 and nearly every known timezone is already accounted for so you really have no choice but to rethink your design if this isn't enough.