I am having an issue when the date from JQuery DatePicker is selected and used as a variable in my SQL Statement. It brings up an error saying invalid datetime string even when I formatted it using DateTime.Parse or Convert.DateTime.
JQuery DatePicker
<script>
$( function() {
$("#datepicker").datepicker({
altField: "#ContentPlaceHolder1_selectDate",
defaultDate: $('#ContentPlaceHolder1_defaultDate').val(),
dateFormat: "mm-dd-yy",
onSelect: function (date, obj) {
$('#ContentPlaceHolder1_defaultDate').val(date);
$('#ContentPlaceHolder1_selectDate').val(date)
$('#ContentPlaceHolder1_defaultDate').trigger('change');
$('#form1').submit();
},
});
});
</script>
<script>
$(document).ready(function () {
onLoad: $('#ContentPlaceHolder1_defaultDate').val($('#ContentPlaceHolder1_selectDate').val());
});
</script>
<div id="datepicker"></div>
<input type="text" id="defaultDate" runat="server"/>
<input type="text" id="selectDate" runat="server" />
<asp:Label ID="Label1" runat="server" />
UPDATE:
This issue is the Postback. If I do this code. It works fine
if (IsPostBack)
{
string defDate = selectDate.Value;
DateTime DT = DateTime.Parse(defDate);
label1.Text = DT.ToShortDateString();
}
However this causes the error message
if (!IsPostBack)
{
string defDate = selectDate.Value.Replace('-', '/');
DateTime DT = DateTime.Parse(defDate);
label1.Text = DT.ToShortDateString();
}
This code works
if (!IsPostBack)
{
string defDate = DateTime.Now.Date.ToShortDateString();
DateTime DT = DateTime.Parse(defDate);
label1.Text = DT.ToShortDateString();
}
else
{
string defDate = selectDate.Value.Replace('-', '/');
DateTime DT = DateTime.Parse(defDate);
label1.Text = DT.ToShortDateString();
}
Can someone explain the reason for this?
DateTime.Parse only takes 4 different formats.
2018-09-14
09/14/2018
Sep 14 2018
14 Sep 2018
It will not accept mm-dd-yy format.
Try replacing the - with / like the following.
defDate.replace('-', '/');
Related
I have a textbox: txtDepartureDate where a user can select the departure date. If the selected date is before today, then I was to show an error message. I have tried using the moment library in Javascript to achieve this and also used the oninput() event handler. I am trying to subtract today's date with the departure date to get the total number of days and if this is less than or equal to zero, then lblError should display the error message. The validation part is not working for me.
Textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
Script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
This is how it is done:
var inputDate = moment([1990, 0, 01]);
var todayDate = moment().toDate();
inputDate.diff(todayDate, 'days')
You have to get entered input date in the above format.
Please i want to get value of month and year from this javascript code as PHP variable $mm = ? && $ yy = ?
input name="startDate" id="startDate" class="date-picker"
<script>
$(function () {
$('.date-picker').datepicker({
dateFormat: "mm/yy",
changeMonth: true,
changeYear: true,
showButtonPanel: true,
onClose: function (dateText, inst) {
function isDonePressed() {
return ($('#ui-datepicker-div').html().indexOf('ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all ui-state-hover') > -1);
}
if (isDonePressed()) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1)).trigger('change');
$('.date-picker').focusout(); //Added to remove focus from datepicker input box on selecting date
}
},
beforeShow: function (input, inst) {
inst.dpDiv.addClass('month_year_datepicker');
if ((datestr = $(this).val()).length > 0) {
year = datestr.substring(datestr.length - 4, datestr.length);
month = datestr.substring(0, 2);
$(this).datepicker('option', 'defaultDate', new Date(year, month - 1, 1));
$(this).datepicker('setDate', new Date(year, month - 1, 1));
$(".ui-datepicker-calendar").hide();
}
}
});
});
</script>
From the comment:
"I am using this html code"
<input name="startDate" id="startDate" class="date-picker" />
<?php if(isset($_POST['month'])) {
$month= $_POST['mm']; echo $month;
$year= $_POST['yy']; echo $year;
} ?>
<input type="button" name="submit" />
Looking at your code you're not actually passing through variables called mm and yy (or month for that matter) - that's not what datepicker.dateFormat does - it merely formats the string going into your input field (e.g. startDate) - so you're explicitly excluding the day.
You can pass that date to the server and load it into a DateTime object.
You can use DateTime::createFromFormat() to do this but you need to add 01 for the day when you create the object otherwise today's date will be used and that can lead to some unexpected results (e.g. the date being set to the 30th of February).
<?php
if(!empty($_POST['startDate'])) {
$startDate = DateTime::createFromFormat('d/m/y', "01/{$_POST['startDate']}");
// to output the month as 'mm'
echo $startDate->format('m')
// to output the year as 'yy'
echo $startDate->format('y');
}
You never have to use the day value stored in the DateTime object but it does need to be there.
Example
If you wanted to put the mm/yy string back into your <input ... /> field after form submission, say it failed validation but you want to keep the data the user entered in the input:
<?php
$startDateValue = !empty($_POST['startDate']) ?
" value=\"" . (DateTime::createFromFormat('d/m/y', "01/{$_POST['startDate']}")->format('m/y')) . "\"" :
"";
?>
<input name="startDate" id="startDate"<?= $startDateValue; ?> class="date-picker" />
References
PHP DateTime class
PHP Date formats
Picture input form where user submits from 1 up to 4 dates within same month. I have set like this:
//hardcoeding rage dates from March 6 to March 9.
app.controller...
$scope.rangeValidator = {
startDate: '06/03/2017',
endDate: '09/03/2017'
}
//Setting calendar available start and end date.
$scope.initCalendar = function() {
$('#reclamoFecha .input-group.date').datepicker({
multidate: true,
multidateSeparator: ",",
format: "dd/mm/yyyy",
startDate: $scope.rangeValidator.startDate,
endDate: $scope.rangeValidator.endDate,
language: "es"
});
};
I want to check if ONLY inputs of dates in this range are submitted, and if false, an alert is executed. When user datepicker input it is logged as a String, also when many dates are submitted each date becomes part of the logged string, so I had to split into an array.
// returns: "06/03/2017,07/03/2017,08/03/2017,09/03/2017"
$scope.validRangeDate = $rootScope.reclamo.fechas.split(',');
$scope.validateForm(function() {
$scope.validRangeDate = $rootScope.reclamo.fechas.split(',');
console.log($scope.validRangeDate);
//returns: ['06/03/2017','07/03/2017','08/03/2017','09/03/2017',]
so what I need to do is a conditional where I can check the if eg: 20/03/2017 is submited it triggers an alert.
I was thinking about setting a range between startdate and enddate with "every" method for the array.
I´m not quite sure if I should convert the string to Date before. Also not quite sure how to use that method on a function.
To check a date in a range you could create a custom validation method like:
$.validator.addMethod("dateRange", function(value, element, params) {
try {
var date = new Date(value);
if (date >= params.from && date <= params.to) {
return true;
}
} catch (e) {}
return false;
}, 'Date out of range');
Then add the relative class rules in order to pass the two parameters for the valid range:
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
}
});
Finally add the validator to your field / fields:
$("#myField").addClass("myDateFieldRangeValidate");
See following complete example:
var fromDate = new Date("2017-03-01");
var toDate = new Date("2017-03-31");
$.validator.addMethod("dateRange", function(value, element, params) {
try {
var date = new Date(value);
if (date >= params.from && date <= params.to) {
return true;
}
} catch (e) {}
return false;
}, 'Date out of range');
$.validator.addClassRules({
myDateFieldRangeValidate: {
dateRange: {
from: fromDate,
to: toDate
}
}
});
$("#myField").addClass("myDateFieldRangeValidate");
$("#frm1").validate();
$("#btnValidate").click(function() {
console.log($("#frm1").valid())
});
jQuery(function($) {
var validator = $('#frm1').validate({
rules: {},
messages: {}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<form id="frm1">
Date
<input type="text" id="myField" value="16 Feb 2017">
<input type="button" id="btnValidate" value="Validate">
</form>
I hope it helps you, bye.
I have the following code to compare two dates with the following conditions
Scenario:
On load there are two text boxes (FromDate, ToDate) with Ajax calendar extenders.
On load From Date shows today's date.
when date less than today was selected in both text boxes(FromDate, ToDate), it alerts user saying "You cannot select a day earlier than today!"
When ToDate's Selected date < FromDate's Selected Date, alerts user saying "To Date must be Greater than From date." and at the same time it clears the selected Date in ToDate Text box.
Codeblock:
ASP.NET , AJAX
<asp:TextBox ID="txtFrom" runat="server"
ReadOnly="true"></asp:TextBox>
<asp:ImageButton ID="imgBtnFrom" runat="server" ImageUrl="~/images/Cal20x20.png" Width="20" Height="20" ImageAlign="TextTop" />
<asp:CalendarExtender ID="txtFrom_CalendarExtender" PopupButtonID="imgBtnFrom"
runat="server" Enabled="True"
OnClientDateSelectionChanged="checkDate"
TargetControlID="txtFrom" Format="MMM d, yyyy">
</asp:CalendarExtender>
<asp:TextBox ID="txtTo" runat="server"
ReadOnly="true"></asp:TextBox>
<asp:ImageButton ID="imgBtnTo" runat="server" ImageUrl="~/images/Cal20x20.png" Width="20" Height="20" ImageAlign="TextTop" />
<asp:CalendarExtender ID="txtTo_CalendarExtender"
OnClientDateSelectionChanged="compareDateRange"
PopupButtonID="imgBtnTo"
runat="server"
Enabled="True" TargetControlID="txtTo"
Format="MMM d, yyyy">
</asp:CalendarExtender>
<asp:HiddenField ID="hdnFrom" runat="server" />
<asp:HiddenField ID="hdnTo" runat="server" />
C# Code
protected void Page_Load(object sender, EventArgs e)
{
txtFrom.Text = string.Format("{0: MMM d, yyyy}", DateTime.Today);
if (Page.IsPostBack)
{
if (!String.IsNullOrEmpty(hdnFrom.Value as string))
{
txtFrom.Text = hdnFrom.Value;
}
if (!String.IsNullOrEmpty(hdnTo.Value as string))
{
txtTo.Text = hdnTo.Value;
}
}
}
JavaScript Code
<script type="text/javascript">
function checkDate(sender, args) {
document.getElementById('<%=txtTo.ClientID %>').value = "";
if (sender._selectedDate < new Date()) {
alert("You cannot select a day earlier than today!");
sender._selectedDate = new Date();
// set the date back to the current date
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
//assign the value to the hidden field.
document.getElementById('<%=hdnFrom.ClientID %>').value = sender._selectedDate.format(sender._format);
//reset the to date to blank.
document.getElementById('<%=txtTo.ClientID %>').value = "";
} else {
document.getElementById('<%=hdnFrom.ClientID %>').value = sender._selectedDate.format(sender._format);
}
}
function compareDateRange(sender, args) {
var fromDateString = document.getElementById('<%=txtFrom.ClientID %>').value;
var fromDate = new Date(fromDateString);
if (sender._selectedDate < new Date()) {
alert("You cannot select a Date earlier than today!");
sender._selectedDate = "";
sender._textbox.set_Value(sender._selectedDate)
}
if (sender._selectedDate <= fromDate) {
alert("To Date must be Greater than From date.");
sender._selectedDate = "";
sender._textbox.set_Value(sender._selectedDate)
} else {
document.getElementById('<%=hdnTo.ClientID %>').value = sender._selectedDate.format(sender._format);
}
}
</script>
Error Screen(Hmmm :X)
Now in ToDate, when you select Date Earlier than today or Date less than FromDate, ToDate Calendar shows NaN for Every Date and ,0NaN for Year
It looks like the format method is assuming a numeric argument, but is being passed a string argument. Comment out both else blocks to confirm this. The if blocks seem to always return false for the following reasons:
Since the two dates are strings, their lengths are compared, not their dates
Use Date.parse() on each date to do a numeric comparison
Validate your date format with a hardcoded value, e.g. Date.parse("May 1, 1999")
I have an ASP.Net form in which users can choose the date from Calendar Extender control, I have 2 fields for the date (FromDate & ToDate).
I want to validate the following using javascript:
FromDate should be always less than ToDate
FromDate & ToDate should not be less than today's date.
If both conditions are true, I would like then to call a method from the codebehind which will calculate the total number of days within the selected period excluding the weekends and display it to the user (this method works fine).
In the code below I tried __doPostBack to fire the codebehind method when the two previously mentioned conditions are met. It fires the codebehind method but then javascript variables becomes incorrect (compareDate variable is always increment on each function call & postback) and thus all the result becomes incorrect.
*Below is the current method I use to validate the date using Javascript, it's fired from OnClientDateSelectionChanged event from both textboxes's calendar extender controls *
<script type="text/javascript">
var fromDate = new Date();
var toDate = new Date();
function checkDate(sender, args) {
if (sender.get_id() == 'CalendarExtenderFrom') {
fromDate = sender._selectedDate;
}
else if (sender.get_id() == 'CalendarExtenderTo') {
toDate = sender._selectedDate;
}
// Check if selected date is less than today's date
var todayDate = new Date();
var year = todayDate.getFullYear();
var month = todayDate.getMonth();
var day = todayDate.getDate();
var dateOnly = new Date(year, month, day);
if (sender._selectedDate < dateOnly) {
alert("You cannot select a day earlier than today!");
sender._textbox.set_Value("");
return;
}
// Check if FromDate > ToDate
if (document.getElementById('TextBoxDateOfLeave').value != "" && document.getElementById('TextBoxDateOfReturn').value != "") {
var compareDate = new Date(fromDate.getFullYear(), fromDate.getMonth(), (fromDate.getDate()) + 1, 00, 00, 00, 00);
if (toDate < compareDate) {
alert("(Return Date) should be greater than (Travel Date)");
sender._textbox.set_Value("");
return;
}
}
// If both conditions are met
window.__doPostBack('__Page', '');
}
</script>
ASP.Net Controls:
<asp:TextBox ID="TextBoxDateOfLeave" runat="server" ClientIDMode="Static" ontextchanged="CalculateLeaveDays"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderFrom" runat="server" Enabled="True" Format="dd/MMM/yyyy" TargetControlID="TextBoxDateOfLeave" OnClientDateSelectionChanged="checkDate" />
<asp:TextBox ID="TextBoxDateOfReturn" runat="server" ClientIDMode="Static" ontextchanged="CalculateLeaveDays"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtenderTo" runat="server" Enabled="True" Format="dd/MMM/yyyy" TargetControlID="TextBoxDateOfReturn" OnClientDateSelectionChanged="checkDate" />
Please let me know if there is a way to achieve this.
Thank you,
Were you looking for something like this? I added a Fiddle here. I used the jquery ui date picker, but you can use any datepicker of your choice, provided the values are in 'yyyy/mm/dd' or 'mm/dd/yyyy' I think