Convert UK date format to American - c#

I have a JQuery date picker which puts the date into a textbox in format DD/MM/YYYY.
I am trying to store this in SQL Server 2008 which needs to accept the date as MM/DD/YYYY, how should I format the date to get this to work correctly?
This is the code to add a my parameter to the query, which causes an error as the day and the month are the wrong way round
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", fixtureDateTextBox.Text);

Never, ever directly insert input text into a parameter as you're doing - it's the root cause of too many security vulnerabilities and holes. Parse the input into a DateTimeOffset object first (you can also use DateTime, but the Offset is better in general to use) by calling DateTimeOffset.Parse(...), then you can simply add it as a parameter without modifying it.
EDIT: I re-read your question, and realized that while the above isn't wrong, it does miss some important things that address your question. See this for how to configure the date picker to display an alternate date format from what it stores in an alternate field:
EDIT 2:
You'll want to parse your DateTime object using the overload which allows you to pass in an IFormatProvider instance.
See http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx for an example of how to do what you're looking to do. Otherwise, DateTime.Parse('13/3/2013') will fail due to unrecognized format.
DateTime.Parse('13/3/2013', new CultureInfo("en-GB").DateTimeFormat) is what you want to do with the input box.

I agree with the other folks that you should be able to configure the JQuery picker format to begin with, but if you can't, this should do the trick:
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
DateTime fixtureDate = DateTime.Parse(fixtureDateTextBox.Text, new CultureInfo("en-GB"));
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", fixtureDate.ToString(new CultureInfo("en-US"));

Try this:
TextBox fixtureDateTextBox = (TextBox)Master.FindControl("ContentPlaceHolderMenu").FindControl("datepicker");
DateTime date = DateTime.Parse(fixtureDateTextBox.Text);
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", date);

Add in the namespaces section: using System.Globalization;
then parse your input date as follows:
string DB_Date = (DateTime.Parse(fixtureDateTextBox.Text)).ToString(new CultureInfo("en-US"));

DateTime UKDate = Convert.ToDateTime(datepicker.Text);<br>
string usDate= UKDate.ToString("dd-MM-yyyy");<br>
SqlParameter fixtureDateParam = new SqlParameter("#fixtureDate", usDate);

Related

convert date string to date time c#

I have this confusion of converting 23/09/21 or 09/23/21 to a valid datetime
23/09/21 refers to development environment ,
09/23/21 refers to customer deploy environment
string _tmpCreatedDate = ((SAPbouiCOM.EditText)b1MatrixUser.Columns.Item("Col_8").Cells.Item(i + 1).Specific).Value;
hence becomes string _tmpCreatedDate = "23/09/21";
DateTime _swapCreatedDate = Convert.ToDateTime(_tmpCreatedDate);
above code will output string was not recognized as a valid DateTime.
tried _tmpCreatedDate = Convert.ChangeType(_tmpCreatedDate, typeof(DateTime)).ToString();
as well, same convert issue, as the input string is dynamic dd/MM/yy or
MM/dd/yy
how to handle this in correct way?
I think you can simply use DateTime.ParseExact
DateTime dt = DateTime.ParseExact(_tmpCreatedDate , "MM/dd/yyyy",CultureInfo.InvariantCulture);
Read more over here CultureInfo.InvariantCulture Property and DateTime.ParseExact
Added as comment, but to OP request, I am adding an answer:
You could specify date format in config in your application or detect in code, at app startup if it's development mode, then you can save appropriate format in some global variable.
One of ideas, if you're using dependency injection, would be to define some date provider service or even you could try specifying own IFormatProvider or something like that, and then using it in parsing methods of DateTime.

C# Date Time Picker to Text?

Im trying to get a text from a file into date format for a label.
What i currently have works great for a DateTimePicker however im wanting to now use a label to display the date rather than a DateTimePicker.
This is what currently works when getting the value to a DateTimePicker:
dateTimeMFR.Value = this.myKeyVault.MFRDate;
and this is what im attempting to make work in a label:
DateTimePicker myDate = new DateTimePicker();
myDate.Value = myKeyVault.MFRDate;
txtMFR.Text = myDate.Text;
Thanks for any help on the matter.
It depends on the format which you want to show the date in. If it should be default user format, then this:
txtMFR.Text = myKeyVault.MFRDate.ToString();
is sufficient.
You can also manually format DateTime as date or time by calling ToShortTimeString or ToShortDateString or combinations of them. Or you can provide one of the predefined string formats as explained here or here. For example:
txtMFR.Text = myKeyVault.MFRDate.ToString("T");
I don't understand why are you not just calling DateTime.ToString.
txtMFR.Text = myKeyVault.MFRDate.ToString();
If you want custom format, you can specify it like this
txtMFR.Text = myKeyVault.MFRDate.ToString("yyyy MMM dd HH:mm:ss");
First pick the format you would like to display it as:
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Then do:
txtMFR.Text = myKeyVault.MFRDate.ToString([put your selected format here]);
label1.Text = dateTimePicker1.Value.ToShortDateString();
This will do it.

How to store date from text box in SQL Server through C# ASP.net

I am having trouble while storing date in sql server DB through C# asp.net, online
I have used asp Text box and asp calender extender in ASP file to get date from user,
<asp:TextBox runat="server" ID="txt_date"></asp:TextBox>
<asp:CalendarExtender runat="server" ID="cal_date" TargetControlID="txt_date"></asp:CalendarExtender>
code behind file is, assume connection and command are declared and initialized ,
mycom = new SqlCommand("insert into mytable(dtCol1) values('"+Convert.ToDateTime(txt_dob.Text).ToString("dd-MMM-yyyy") + "')", mycon);mycom.ExecuteNonQuery();
Problem is, when I select date less than 12 of any month it works perfect,
but when date/day is greater than 12 of any month it gives error,
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
I have tried all combinations of .ToString("dd-MMM-yyyy")
Please Help
thanks in advance
try this
mycom = new SqlCommand("insert into mytable(dtCol1) values(#value1)");
mycom.Parameters.AddWithValue("#value1",Convert.ToDateTime(txt_dob.Text));
mycom.ExecuteNonQuery();
Try this
CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyles style = DateTimeStyles.None;
DateTime dt;
DateTime.TryParseExact(txt_dob.Text, "m-d-yyyy", provider, style, out dt);
mycom = new SqlCommand("insert into mytable(dtCol1) values(#datevalue)", mycon);
cmd.Parameters.Add("#datevalue",SqlDbType.DateTime).Value =dt;
mycom.ExecuteNonQuery();
The problem seems to come from here: Convert.ToDateTime(txt_dob.Text). This type of conversion is not good because:
It disregards the format that the control uses. Convert.ToDateTime(...) expects the string to be in a certain format(s) in order to parse it correctly. This cannot handle any custom formats that the txt_dob could use.
It is ignorant of culture-specific formatting. Internally, Convert.ToDateTime(...) will probably stick to CultureInfo.CurrentCulture, which is not said to be capable of parsing the date. Also, some front-end controls in .NET recognize and use the client culture passed by the browser (for web apps), and it is likely for that culture to be different than the server culture. CultureInfo.CurrentCulture will represent the server-side culture and formatting discrepancies are possible to occur
If you know the format of the txt_dob.Text you have to explicitly parse it. In the example below I have assumed the format is "MM/dd/yyyy":
String dateFormat = "MM/dd/yyyy";//The format that the txt_dob control uses
DateTime parsedDate = DateTime.ParseExact(
txt_dob.Text, dateFormat, CultureInfo.InvariantCulture);
You can also check this related topic with some additional information on a similar case like yours
TLDR; You're using the wrong DateTime format.
There's plenty of issues here that will blow up Death Stars, left right and center.
Firstly, you're creating the sql query on the fly - that's probably the biggest no-no in the last 10 years and everyone has stopped doing that. In other words, please please please don't start doing (the very out of date) ADO.NET programming to pass data from the website to the database. Modern replacements like Entity Framework, NHibernate or even Linq2Sql if you're desperate.
Ok - that said, lets try and answer your question none-the-less.
The reason is because u're passing in the values in the wrong format. You're doing dates first. Your sql server is probably wanting it to be MONTHS first. Because it's probably been setup to be style 121 (<-- that's a real technical sql server setting thing for Compatibility crap..)
But don't try and fight and guess.
Lets use a more universal and start string format: yyyy-mm-dd hh:mm:ss.ms
eg.
SELECT CAST('2013-02-08 09:53:56.223' as DateTime)
And you can see this in action over at SQLFIDDLE.
This is a really good StackOverflow question that explains what the default DateTime format is, etc.
Use this:
mycom = new SqlCommand("insert into mytable (dtCol1) values ('" + Convert.ToDateTime(txt).ToString("MMM-dd-yyyy") + "')", mycon);
Thanks
User DateTime.ParseExact() in place of Convert.ToDateTime() method.
dateString = "12-31-2012";
format = "MM-dd-yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
[Date_Of_Birth]='" + Convert.ToDateTime(TxtDate_Of_Birth.Text).ToString("MM-dd-yyyy") + "'
Will help the cause of error that sqlserver accepts datetime in format MM/dd/yyyy, but not in dd/MM/yyyy.

How to convert MM/dd/yyyy to yyyy/MM/dd in C# using globalization

I have a text box in which a user is supposed to enter a date in MM/dd/yyyy format. This date is stored as yyyy/MM/dd in the database.
I want the user to enter the date in MM/dd/yyyy format and later I want to convert it to yyyy/mm/dd so that I can query the database.
How can I convert the user input date MM/dd/yyyy to yyyy/mm/dd?
If you're certain of the input string's format, use DateTime.ParseExact specifying "MM/dd/yyyy", then return the DateTime using .ToString with the appropriate "yyyy/MM/dd" format string.
There's no need to reference anything in the System.Globalization namespace for this.
That said, your database should be storing dates with a datetime format, rather than a string, in which case the format doesn't matter as your DBMS should do the conversion for you.
You can parse the date and format the result:
string str = Date.Parse(myDate).ToString("yyyy/MM/dd");
Alternatively, if the current culture doesn't support that date format and you've already validated the input:
string items[] = myDate.Split('/');
string str = items[2] + "/" + items[0] + "/" + items[1];
When you said globalization, I assume you want the change to be automatic according to current culture
You can setup culture (at Global.asax.cs I suggest)
System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("the culture you want to set"); //
you do not need to touch any datetime thing, it just happened when you output them.
One thing is not the other.
Not sure why you want to insist on the text entered being MM/dd/yyyy, or why you haven't used a date time picker to make sure it is a date.
But at the point you get the content of the textbox as a date, parse it based on globalisation, or a set of acceptable formats. Now it is a date, and assuming it's a date in the database, format is irrelevant until you come to populate the text box, with some content from the DB, inwhich case you use DateTime's ToString method witha globalisation parameter, usually CultureInfo.CurrentCulture, or if you've got away with it CultureInfo.InvariantCulture.
If it's a string in the DB, then this is the least of your problems.
They key point is if you use dates properly, format is only relevant for Parse, and ToString type methods.
i am using
IFormatProvider culture=new CultureInfo("en-GB",true);
sqlcommand cmd=new sqlcommand("query",con);
cmd.Parameters.AddWithValue("#date",DateTime.Parse(txtdate.Text.Trim(),culture,DateTimeStyles.NoCurrentDateDefault).Date);
for this to work the format property must be set to dd/MM/yyyy
and text box read only property must be false

How to make DateTime independent from the current culture?

I cam trying to convert a datetime to string and back, but making it so that it works for all cultures.
I basically have a Textbox (tbDateTime) and a label (lbDateTime). The label tells the user, in which format the software expects the input of tbDateTime. The input of the Textbox will be used for an MySQL command.
Currently it works like this:
lbDateTime.Text = "DD.MM.YYYY hh:mm:ss"; // I live in germany
DateTime date = Convert.ToDateTime(tbDateTime.Text);
String filter = date.ToString("yyyy-MM-dd HH:mm:ss");
Now my question:
Is it possible to determine the format-string for lbDateTime.Text based on the current culture?
Which format does the Convert.ToDateTime function uses?
I hope you can help me. I have actually no pc here to test different cultures, so I'm very afraid that I make something wrong.
Instead of using the Convert.ToDateTime method you can use the DateTime.Parse or DateTime.ParseExact methods. Both allow you to pass a culture that tells how you expect the date to be formatted.
The DateTime.ParseExact method also allows you to specify the format you expect, so you can parse more or less any format with this method.
Edit:
Regarding Convert.ToDateTime. The documentation says that the current culture is used when parsing: http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx
The current culture can be found using the System.Threading.Thread.CurrentThread.CurrentCulture property.
Edit2:
Oh. You may also want to use DateTime.TryParse and DateTime.TryParseExact if you are unsure whether the given format is invalid.
Edit3:
Lots of edits here... I see that you want to determine the culture string that matches the date the user has entered. There is no general solution that is guaranteed to work here. Say for instance that the user has entered the date 01.02.11. There is no way to be certain if this date is in day.month.year or month.day.year or year.month.day and so on.
The best you can do is to have a list of expected input cultures and start with the most likely and try to parse the date using that. If that fails, you can try the second most likely and so on...
But this is really not recommended. Either give the user an expected format, or better, use a date input box that ensures that you receive the selected date in an appropriate format.
The Convert.ToDateTime method will call DateTime.Parse to parse the string, using the current culture (CultureInfo.Current).
You can specify a culture when parsing the string. Example:
DateTime data = DateTime.Parse(tbDateTime.Text, new CultureInfo("en-GB"));
You can use DateTime.ParseExact (or DateTime.TryParseExact) to parse the string using a custom date format. Example:
DateTime data = DateTime.ParseExact(tbDateTime.Text, "dd'.'MM'.'yyyy HH':'mm':'ss", CultureInfo.InvariantCulture);
Another solution :
// Specify the current language (used in the current system you are working on)
CultureInfo currentCulture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.ToString());
// Specify the language that we need
CultureInfo myLanguage = CultureInfo.GetCultureInfo("en-US");
// Adapt the DateTime here, we will use the current time for this example
DateTime currentDate = DateTime.Now;
// The date in the format that we need
string myDate = DateTime.Parse(currentDate.ToString(), currentCulture).ToString(myLanguage);

Categories

Resources