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.
Related
I want datetime.now to return the datetime object in UK format. It does so on my local computer but when I upload the code to the server it does it in US format
DateTime doesn't have any format associated with it. Formatting is just for presentation. You can do:
string formattedDate = DateTime.Now.ToString(CultureInfo.CreateSpecificCulture("en-GB"));
Or supply a specific/custom format like:
string formattedDate = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
I want datetime.now to return the datetime object in UK format.
There's no such concept, any more than an int is a value "in hex" or "in decimal". A DateTime is just a DateTime - you can specify the format when you convert it to a string. It's really important to understand the difference between an inherent value, and what it looks like after it's converted to text - very few types are aware of a custom, modifiable format to use when converting themselves - it's either provided externally (as for DateTime, numbers etc) or simply fixed.
Before you convert start hard-coding a UK format though, I would strongly advise you to consider exactly what you're doing:
Ideally, avoid the conversion in the first place. A lot of the time, string conversions are unnecessary and can be problematic.
Is the text going to be consumed by another machine? Use an ISO-8601 standard format.
Is the text going to be consumed by a person? Use their culture rather than some arbitrary one you decide on.
... Or display it in a dedicated control...
You can use the overload of the ToString method: ToString("dd/MM/yyyy"), or: ToString("yy/MMM/dd"), etc. etc.
Read more about it here: https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx
Also sounds to me that you might want to configure your (UI-)Culture in the web.config? Then it will always be in the same format regardless of the culture of your US/Japanese/european server culture..
More about that here: https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
LogDate = DateTime.UtcNow.AddHours(1);
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);
I have a date and time which should be copied to DateTime object without changing its format.
Is there a way to resolve it?
Pls see the code below
string dateTime = "07/20/11 14:40:28";
DateTime copyDateTime = Convert.ToDateTime(dateTime);
string dateTime2 = copyDateTime.ToString();
Output:
{7/20/2011 2:40:28 PM}
If you notice the output, it got changed to PM. I want it as it is. How to get it?
EDIT:
I want dateTime2 to have the value exactly as it was for dateTime.
Format is not intrinsically associated with the DateTime. Format is simply a display property.
If you need to display it in your preferred format than simply call:
Console.WriteLine(copyDateTime.ToString("G"));
See MSDN for a complete list of standard format strings.
Before outputting, you need to convert the DateTime back into a string. By default, it simply calls "ToString" which uses the default DateTime format configured for the current user/locale.
Use ToString and specify a format to convert the datetime back into a String, then you can control the format.
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);
string Edate = collection["effectiveDatePicker"].ToString();
string Cdate = collection["cancelDatePicker"].ToString();
The Date I am getting is 20101112 or 20101116
Then I am doign soemthign like this to assing my Datetime variable
h.Edate= DateTime.ParseExact(collection["effectiveDatePicker"].ToString(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture, DateTimeStyles.NoCurrentDateDefault);
h.CDate= DateTime.ParseExact(collection["cancelDatePicker"].ToString(), "yyyyMMdd", System.Globalization.CultureInfo.CurrentCult
After saving to the data base.. I am seeing the EDate and CDate fileds somethign like this
11/10/2010
11/15/2010
with the same dates when I Submit again I am getting Error in the ParseExact bec the string I am getting is 11/10/2010 but its expecting 20101010
Can any body help me out?
You can specify the format that your dates are coming in as like this:
string Edate = collection["effectiveDatePicker"].ToString("yyyyMMdd");
string Cdate = collection["cancelDatePicker"].ToString("yyyyMMdd");
This should ensure that you are working with strings that look like what you want.
I can tell you for sure that there is a reformatting problem. I don't fully understand your code and the steps it takes (I guess you are using data binding or something similar).
The point seems that dates are initially set as yyyyMMdd, but when you postback the ToString() operator is applied to these dates, converting them to your OS's native format MM/dd/yyyy.
You must force them to be converted into yyyyMMdd again, because by default ToString will use CurrentUICulture which is not good for you.
You should show us the update code
I'm not sure what your specific question is. Because you're using DateTime.ParseExact() and are specifying a format of 'yyyyMMdd', passing in a string such as '11/04/2010' will fail.