I have a c# winforms app which is databound to table with multiple dates. The client requires that date can by inputted using a text-box. However, I cannot get it to work like it should. The problem is when I leave the textbox the day and month change places. So when I type 9-12-1950 it will show up as 12-09-1950. Same when I type 09-12-1950. Internally the date is stored as yyyy-MM-dd. Databinding is enabled using the format dd-MM-yyyy. I use the validating event t0 check if the date is valid like:
if (DateTime.TryParseExact(tbDate.Text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
tbDate.Text = String.Format("{0:dd-MM-yyyy}", dateValue);
When I debug I see that the text-value of tbDate is still in the right format, in my case 9-12-1950 for example. I also see that the dateValue which is returned from the TryParseExact holds the same date, but in the format of MM/dd/yyyy.
Saving the date to the database is set onValidation. What am I missing here?
[Update]
Maybe I was not clear enough on my explanation. The date is stored in the SQL Db in the format yyyy-MM-dd of type DateTime (not varchar). On my form I want to show and edit it as dd-MM-yyyy (There are some other formats too like: "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy", "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy","dd-MM-yyyy", "dd-M-yyyy", "d-M-yyyy", "d-MM-yyyy","dd-MM-yy", "dd-M-yy", "d-M-yy", "d-MM-yy".
The typing is working, but as soon as I move away from the TextBox the day and month change place. I think I miss something. Just don't know what.
I feel a little stupid, the problem was caused by the local system setting, which was set to M/d/yyyy. I changed it to my local culture dd-MM-yyyy which solved the problem.
Related
I am trying to take a time string in the format of HH:MM such as 18:30 and turning this into a DateTime string.
I have tried many different methods such as using ParseExact (as seen below), however even when using this code, it still outputs the DateTime string as both the date and the time.
dtpTime.Value = DateTime.ParseExact(Classes.SystemClasses.Booking.getBookingTime(), "H:mm", null, System.Globalization.DateTimeStyles.None);
Which outputs:
20/02/2019 18:56:00
The value in Classes.SystemClasses.Booking.getBookingTime() is 18:56 which is the value I wish to enter into a DateTimePicker on a form in the format of HH:MM
Any help to resolve this problem would be greatly appreciated and if the explanation is not clear enough, please feel free to ask myself any questions.
Thanks, Ryan.
What you are trying to do is hold a TIME inside a DateTime variable. That is not possible, as the name suggest, this type is used to hold a Date and a Time. If you need only the Time part of the date, you need to convert it to a string:
var time = DateTime.ParseExact(Classes.SystemClasses.Booking.getBookingTime(), "HH:mm", null, System.Globalization.DateTimeStyles.None).ToString("HH:mm");
Frustrating problem with DateTime, we have a section with a date picker on and if the culture is set to en-GB and the date is 01/11/2012 (dd/mm/yyyy) and then the culture is swapped to Chinese (zh-CN) the date is passed in the old culture format and when it is converted to a DateTime the datetime becomes 2012/1/11 when the culture should be (yyyy/mm/dd).
This seems to be the only culture that I have come across where the conversion is going wrong as it should be 2012/11/1 as 11 is the month.
Does anyone have any ideas why it isn't converting correctly?
Sorry guys this is my fault for not being clear enough, more detail needed.
We have a reporting form that allows users to select a date range, on that form we use use a date range picker (http://www.filamentgroup.com/lab/update_date_range_picker_with_jquery_ui/) to populate a readonly textbox that is submitted to filter the results. Users can select from a dropdown their current culture (needed for our users as they wanted to easily swap between English and Chinese without changing browser settings, If the culture is en-GB then the date range string may read "01/01/2012---01/11/2012" which is 1st January 2012 - 1st November 2012. This is stored in the url, e.g: &DateRange=01%2F01%2F2012+---+01%2F11%2F2012.
Now if the user swaps to Chinese it calls the current page with all the same query parameters but also with the culture parameter changed (we allow the culture to be overridden by an URL parameter) which means the dateformat 01/11/2012 is in the query string, when we pass this using:
DateTime.TryParse(endDateString, out endDate);
the DateTime object contains a date of 11th January 2012 instead of 1st November 2012.
Is there a way I could store the culture info that the date string is in and use that to convert to the new culture info if the culture is swapped?
Any better ideas would be greatly appreciated, swapping from en-GB to en-IN (India) seems to work fine as does swapping to es-MX (Mexico). It just seems to be chinese but that could be pot luck based on these languages date formats.
Many thanks for taking the time to read this.
DateTime.TryParse(endDateString, out endDate);
is using whatever culture is default on the server.
The basic solution would be:
var ci = GetCultureInfoFromRequest();
DateTime.TryParse(endDateString, out endDate, ci);
Use strings to move datetime around in such cases, if you are not processing datetime and just storing it.After that you can change the format before storing it in the database.
I know such questions are in ton in SO but my situation seems little weird to me.
I have a textbox with a calendar extender control on my aspx page
Default format is "d" in extenders date format property.
When I choose my date say 15th May 2012 from the calendar,it gives me 5/15/2012, which is fine.
Since its a string and my db field is oftype datetime, so I am using
Convert.ToDateTime(TextBox.Text); // TextBox.Text = 5/15/2012
But it throws the exception,
string was not recognized as valid datetime.
I then Change the code and used DateTime.Parse() but the issue remains. Then i tried to reformat the date something like this,
Convert.ToDateTime(string.Format("0:MM-dd-yyyy",TextBox.Text)).Date
but still its throwing exceptions..
Please help me.
Use the following,
DateTime dt = DateTime.ParseExact(TextBox.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
There's probably a difference between your system's DateTime format and the DateTiem format the extender uses.
I suppose that your dev machine date-time format is not equal to MM/DD/YYYY, but something else (for example DD/MM/YYYY). Have a look on your computer Regional settings to see your system date time format.
My C# application have to read some date from MySQL database. Problem I have is that format of date depends on system localisation settings.
My question is if is possible that I always get date in formats yyyy-MM-dd hh:mm:ss, and yyyy-MM-dd, no matter of localisation settings.
Thank you in advance!
If you are storing the dates as true date or datetime values, your application will get the raw binary data back, and it will not be subject to localization until you create a string representation of the date values. My guess is that you are looking at the values in the debugger or using Console.WriteLine(theValue);, which will use the current locale. Always include the desired format and/or the desired culture when converting non-string values to strings.
If you are storing the dates as strings, you will always have to know exactly what format went into the database.
Assuming the dates are stored as date or datetime: just handle the values as they are, and don't convert them to strings until you need to show them to a user:
DateTime theValue = theReader.GetDateTime(fieldOrdinal);
var theValueAsText = theValue.ToString(CultureInfo.InvariantCulture);
var specificTextRepr = theValue.ToString("yyyy-MM-dd HH:mm:ss");
The theValueAsText variable will be a string representation that is not tied to a specific culture. The specificTextRepr will be your specific text representation.
You shouldn't be reading it back as a string from the database - you haven't shown how you're reading the data, but if you use something to populate a DataTable, or LINQ, or IDataReader.GetDateTime then there's no string formatting involved (assuming it's stored properly in the database, which it looks like it is).
A DateTime value doesn't intrinsically have a format, any more than an int is in decimal or hex - it's how you choose to convert it that matters, and you should almost always avoid doing that formatting unless you really need to.
Since you store the dates in date and date/time specific representations, formatting does not play into it at all (as opposed to some highly discouraged storage schemes when date/time is stored as strings, when formatting does matter, but for a wrong reason).
When you query MySQL from your C# code, you will get the correct dates no matter what your locale is. They will be displayed differently based on the locale, but they will represent the proper date regardless of the locale settings.
You can format the date directly in the query by using
date_format(dob,'%d/%m/%Y')
select date_format(dob,'%d/%m/%Y') dob from student where Id=1
Change
CurrentDate = DateTime.Now.ToString("MMM d, yyyy");
CurrentTime = DateTime.Now.ToString("hh:mm tt");
TO
CurrentDate = DateTime.Now.ToString("MMM d, yyyy",CultureInfo.InvariantCulture);
CurrentTime = DateTime.Now.ToString("hh:mm tt", CultureInfo.InvariantCulture);
As you can see in the below screen shot. I have Date which is 7/12/2011 12:00:00 AM. Date is described wrong even if I format it. 7 should be the day and 12 is the month.
How I fix that to get proper formatting for yellow return string?
In the below screen shot the Date is 28/12/2011 11:00 where 28 is day and 12 is month. Trying to convert that string into DateTime to save into SQL Server DateTime field but gives conversion problem. Anyone tell me why is that and How to fix it?
Solution:
I solved problem like below. When I want saving date in SQL Server 2008 r2 the default was saved like 2011-08-12 11:00:00.000 which was causing problem. I changed that formatting Date when it was going to be saved in SQL like below and it worked
DateTime n = Convert.ToDateTime(start_date);
var h = String.Format("{0:dd/MM/yyyy}", n);
if (start_date != "")
{
changedEvent.start_date = Convert.ToDateTime(h);
}
Output now is 2011-12-08 11:00:00.000. Do you think any clean work around?
You should call DateTime.ParseExact(start_date, "dd/MM/yyyy", CultureInfo.InvariantCulture)
Try:
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm:ss TT", null); //28/12/2011 11:00:00 AM
DateTime.ParseExact(str, "dd/MM/yyyy HH:mm", null); //28/12/2011 11:00
I think you are addressing the wrong problem. If you want DateTime to recognize your locale date format, then you should make sure the servers date locale is set for your local one. Then, DateTime will convert the date correctly without conversion.
If that's not possible (say you're using a shared server in a different locale) then the ParseExact method would be one solution, but it will only fix some of the problem. For instance, dates posted and model bound will attempt to parse in the servers locale format.
You may need to set your locale explicitly, using something like this:
Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX");