Hello,
I am trying to save the date field into mysql table.
The date field in my jsp form is in format MM/DD/YYY and in database as YYYY/MM/DD.
How can I retrieve the date from form and insert into the table with YYYY/MM/DD format ?
Sushmitha_1 0 Newbie Poster
Steven_10 0 Newbie Poster
There are several ways to get your date formated before database insertion. A newer way is to take advantage of HTML5's "date" type. The date type works in most newer versions of all the major browsers But keep in mind older browsers (I'm not exactly sure on which ones--google it) won't see the "date" type as anything other than a text field and will not format the date. Here is an example that just writes the formated date back to the screen:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>HTML5 Date Input</title>
<style>
body {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
color: #1B1B1B;
margin-left: 30px;
}
</style>
</head>
<body>
<h1>HTML5 Date Input</h1>
<form id="form1" name="form1" method="post">
<p>
<label for="date">Date:</label>
<input type="date" name="date" id="date">
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
<?php
if (isset($_POST['submit'])) {
echo '<p>The selected date is ' . $_POST['date'] . '.</p>';
}
?>
</body>
</html>
And here is a working example: http://srisservice.com/phpDate/date_input.php
If you know you are going to have older browsers as part of your audience then you can use jQuery to handle it. Here is an example:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<style>
body {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
color: #1B1B1B;
margin-left: 30px;
}
</style>
</head>
<body>
<h1>jQuery UI Datepicker</h1>
<form id="form1" name="form1" method="post">
<p>
<label for="date">Date:</label>
<input type="text" name="date" id="date">
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
<?php
if (isset($_POST['submit'])) {
$parts = explode('/', $_POST['date']);
$date = "$parts[2]-$parts[0]-$parts[1]";
echo '<p>The selected date is ' . $date . '.</p>';
}
?>
<script src="https://code.jquery.com/jquery-1.12.3.min.js";></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script>
$(function() {
$('#date').datepicker({
//dateFormat: 'yy-mm-dd' // << formats it for database insertion with JavaScript << not good for users though
});
});
</script>
</body>
</html>
And here is a working example: http://srisservice.com/phpDate/datepickerTweaked.php
Hope this helps.
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.