Reputation: 4721
I have a textbox and calendar control in my aspx page which is working fine on local machine with dd-mm-yyyy
format.
But when I use the same code on my server it automatically takes mm-dd-yyyy
format. I don't know why this is happening
Below is my code:-
<asp:TextBox ID="txtdatefilter" runat="server" Width="70" OnTextChanged="txtdatefilter_TextChanged" ></asp:TextBox>
<cc3:Calendar ID="CaldatefilterDt" runat="server" CultureName="en-GB" DatePickerImagePath="../Images/icon2.gif"
DatePickerMode="true" TextBoxId="txtdatefilter" Align="Left" OnDateChanged="CaldatefilterDt_DateChanged">
</cc3:Calendar>
CS code
protected void txtdatefilter_TextChanged(object sender, EventArgs e)
{
CaldatefilterDt.SelectedDate = Convert.ToDateTime(txtdatefilter.Text);
}
protected void CaldatefilterDt_DateChanged(Object sender, EventArgs e)
{
txtdatefilter.Text = Convert.ToDateTime(CaldatefilterDt.SelectedDate, CultureInfo.GetCultureInfo("en-GB")).ToString("dd-MM-yyyy");
}
Upvotes: 1
Views: 1553
Reputation: 460038
You can use DateTime.TryParseExact
:
protected void txtdatefilter_TextChanged(object sender, EventArgs e)
{
DateTime dateFilter;
if(DateTime.TryParseExact(txtdatefilter.Text, "dd-MM-yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dateFilter))
CaldatefilterDt.SelectedDate = dateFilter;
}
another option is to use DateTime.Parse
(better TryParse
with user input) and to provide your DateTimeFormatInfo
/ CultureInfo
, for example "en-GB"
(UK) or "de-DE"
(germany):
bool valid = DateTime.TryParse("26-01-2016", new CultureInfo("en-GB"), DateTimeStyles.None, out dateFilter);
The first option works always because it circumvents localization issues by using DateTimeFormatInfo.InvariantInfo
or CultureInfo.InvariantCulture
. The second option ensures that it works with the provided formatinfo/culture.
Upvotes: 3
Reputation: 635
Use this code:
DateTime dt = DateTime.ParseExact(txtdatefilter.Text.ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy");
Upvotes: 0
Reputation: 1762
Use the CultureInfo.InvariantCulture
:
Convert.ToDateTime(txtdatefilter.Text.ToString(), CultureInfo.InvariantCulture);
Upvotes: 0