Get Month and Year from textBox in asp.net - asp.net

I have a textbox from which I choose a date. Based on the selection, I have to get the respective month and year and save it as integer in the database. How do I do this?

If your are using jquery then add option for dateformat and you will have desired format you want
$(function () {
$('.date-picker').datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'MM yy',
onClose: function (dateText, inst) {
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));
}
});
});
Here's is fiddle for same.

Why don't you use a DateTimePicker * instead?
However, if you insist on the TextBox, use DateTime.TryParse to validate and parse a date. Once you have the DateTime you can use it's Month and Year properties.
DateTime dt;
if(DateTime.TryParse(txtDate.Text, out dt))
{
int month = dt.Month;
int year = dt.Year;
}
else
{
MessageBox.Show("Enter a valid date");
}
* Edit since you are using ASP.NET you could use the Calendar control instead of the DateTimePicker. If you're using ASP.NET-Ajax a CalendarExtender is also a good alternative.
From the commets i see that you're using VB.NET ....
Dim dt As Date
If Date.TryParse(txtDate.Text, dt) Then
Dim month As Int32 = dt.Month
Dim year As Int32 = dt.Year
Else
MessageBox.Show("Enter a valid date")
End If

To get the month and year I used the following code.
Dim nStartMonth = Month(txtStartDate.Text)
Dim nStartYear = Year(txtStartDate.Text)
Thanks all for your time and help! :)

Related

String was not recognized as a valid DateTime in C# asp.net

I want to import date value from excel cell. cell value having "10 October 2013" format. I want to convert it to datetime data type. My code getting error "string was not recognized as a valid datetime"
//code
OleDbCommand olecmd = new OleDbCommand("select * from [Sheet1$]", olecon);
OleDbDataReader olerdr = olecmd.ExecuteReader();
while (olerdr.Read())
{
deldate = olerdr.GetValue(13).ToString();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["irisdb"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("procdamandrugs", con);
cmd.CommandType = CommandType.StoredProcedure;
DateTime dt = DateTime.ParseExact(deldate, "MM/dd/yyyy", CultureInfo.InvariantCulture);//getting error in this line
SqlParameter par9 = new SqlParameter();
par9.ParameterName = "#deleffdate";
par9.SqlDbType = SqlDbType.DateTime;
par9.Value = dt;
cmd.Parameters.Add(par9);
cmd.ExecuteNonQuery();
}
}
Do any one help me to solve this issue.
cell value having "10 October 2013" format.
You are giving wrong format in ParseExact that does not match with the date string you are passing. You need different format than you gave. For day you need dd, for month you need MMMM and for year you need yyyy and you have to give spaces as separator.
It is worth the article Custom Date and Time Format Strings on MSDN for using the string formats for date conversion.
DateTime dt = DateTime.ParseExact(deldate, "dd MMMM yyyy", CultureInfo.InvariantCulture);
I recommend the utilizing the DateTime.TryParse method before constructing your SQL objects. Ensure you have quality input before having a conversation with your database.
http://msdn.microsoft.com/en-us/library/ch92fbc1%28v=vs.110%29.aspx
Below is a sample from my own code for an asp.net application
// Validation
DateTime dtOut_StartDate;
if (!DateTime.TryParse(txtStartDate.Text, out dtOut_StartDate))
{
Message = "Start date is not a valid format.";
txtStartDate.CssClass = ErrorCssClass.TextBox;
txtStartDate.Focus();
return false;
}
Select Date Time setting from Right lower bottom & Change the format from here......

Have kept format of ajaxcalendar control as "dd/mm/yyyy" and want to save in database as mm/dd/yyyy

I m using ajax calendar control to a textbox, have set its format as "dd/mm/yyyy" .
Bapur.Date = txtdate.Text;
in data access layer
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = bapur.Date;
on saving, like above ( where Date is a string Bapur is object of businesslayer class)
in the database where datatable in database has date as datetime format.
m getting an error : cant convert string to datetime i dint get error when format was "mm/dd/yyyy" .
Basically, I want users to view date in dd/mm/yyyy but on saving i want it in
mm/dd/yyyy
Have tried a lot but not working.
here is my answer ---- https://stackoverflow.com/a/11720162/1445836 -----
You can use:
DateTime.ParseExact("yourDate","formatinWhichYouWant",culture of current string);
ex:
DateTime dt =DateTime.ParseExact("yourDate","formatinWhichYouWant",culture of current string);
string myDate = bapur.Text.Split("/");
string dateString = myDate[1] + "/" + myDate[0] + "/" + myDate[2];
got my answer
string old = txtdate.Text;
string newDate = DateTime.ParseExact(old, "dd/MM/yyyy", null).ToString("MM/dd/yyyy");
Bapur.Date = newDate.ToString();

Compare two dates in vb.net whether they are equal or not

I have a Date variable startdt and a String variable hdnsdate.
Suppose if startdt has the value in the form 3/1/2012 and hdnsdate has the value in the form 03/01/2012. Than how can i compare that these two dates are equal in vb.net.
In if condition of my program i want to do this check. In case the two dates match move out of if loop otherwise go into the if loop.
E.g A sample in C# what exactly i want.
if(startdt !=hdnsdate)
{
//Do
}
else
{
//Do this
}
Parse hdnsdate (string) to Date type using Parse, ParseExact method and use DateTime.Compare, Equals, CompareTo methods.
String to date
Dim enddate as Date
Date.TryParse(hdnsdate, enddate)
If startdt = enddate Then
'Do this
Else
'Do this
End If
Alternative to compare date:
Dim result = DateTime.Compare(date1, date2)
If result=0 Then
'Do this
End If
You need to parse the string into a DateTime then compare the two.
VB.NET
Dim parsed As DateTime = DateTime.Parse(hdnsdate)
If startdt != parsed Then
Else
End If
C#:
DateTime parsed = DateTime.Parse(hdnsdate);
if(startdt != parsed )
{
//Do
}
else
{
//Do this
}
I suggest looking at the different parsing methods defined on DateTime, as you may need to use a standard or custom date and time format string to ensure the string gets parsed correctly.
Dim result = DateTime.Compare(hdnsdate, date2)
If result=0 Then
'Do this
End If

How do I increment a date by 1 day in VB.NET

If I have a textbox1 and button1, where in textbox1 the date will display as 01-Apr-2011, I want to click on button and have the date in textbox1 increase by 1 day.
So, if textbox1s date is 01-Apr-2011 then in textbox1 after clicking the button, textbox1s date will be 02-Apr-2011, a further click will get 03-Apr-2011 and so on.
How do I do this using VB.NET?
First you use DateTime.ParseExact to get the corresponding date-time instance and then use DateTime.AddDays to add the day and then format the date-time object to string again.
For example,
Dim currentDate as DateTime
currentDate = DateTime.ParseExact(textbox1.Text, "dd-MMM-yyyy", null);
currentDate.AddDays(1)
textBox1.Text = currentDate.ToString("dd-MMM-yyyy")
Assuming that the control is called textbox1 your click handler needs to do something like this:
Dim currentDate as DateTime
' Get the current date from the textbox
currentDate = Convert.ToDate(textbox1.Text)
' Add one day
currentDate = currentDate.AddDays(1)
' Write the date back to the textbox
textBox1.Text = currentDate.ToString("dd-MMM-yyyy")
Note: The exact format of the date written back to textbox1 may not match precisely what you're after - you'll almost certainly want to use DateTime.ToString and choose an appropriate format pattern.
Something extra that I just had to use and is quite obvious, but to minus 1 day from a date in VB.NET you would do the following:
myDate = Mydate.AddDays(-1)
different ways to add one day to a datetime object
Dim dt as DateTime(2011,10,12)
dt = dt.AddDays(1)
dt = dt.AddHours(24)
dt = dt.AddMinutes(1440)
dt = dt.AddSeconds(86400)
result will be 16 that is 12 + 4 days

OnItemDataBound to set row values

I need to set a cell value to something dependant on other values which are only available during data binding so I'm using OnItemDataBound but it says I can't set the dataitem value.
Any ideas how to do this?
protected override void OnItemDataBound(RepeaterItemEventArgs e) {
base.OnItemDataBound(e);
DateTime date = (DateTime)DataBinder.Eval(e.Item.DataItem, "date");
string year = String.Format("{0:yyyy}", date);
string month = String.Format("{0:MM}", date);
((DataRowView)e.Item.DataItem)["url"] = "/" + year + "/" + month;
}
Results in the exception:
System.Data.DataException: Cannot set url.
Well I guess this isn't possible then. I've gotten around the problem by setting the values in the underlying datatable before binding to the repeater.

Resources