String was not recognized as a valid DateTime - c#

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.

Related

String to DateTime conversion not working

I am converting one string to DateTime variable like this
DateTime selecteddatetest = Convert.ToDateTime("09/21/2017");
This works fine in my production Server, But when I run this code in my local development machine, this throws an error
System.FormatException: 'String was not recognized as a valid DateTime.'
Can anyone please point out what I am missing here?
You could use ParseExact if the time format is consistent:
DateTime.ParseExact("09/21/2017","MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture)
Its probably a localisation issue between the two machines, try specifying the date in the format "2017-09-21" and it should work everywhere.
You are likely using a different culture between the two machines.
For example, the server is using the US culture which expects the format MM/dd/yyyy so your parsing works.
You local machine may be using a culture such as UK which expects the format dd/MM/yyyy and as there is no month 21 it fails.
You can specify the culture explicitly if you know it's always going to be the same:
Convert.ToDateTime("09/21/2017", new System.Globalization.CultureInfo("en-US"));
It may also work with an invariant culture:
Convert.ToDateTime("09/21/2017", System.Globalization.CultureInfo.InvariantCulture);
You may also use ParseExact to specify the desired format:
DateTime.ParseExact("09/21/2017", "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

One DateTime parses fine but the other doesn't?

I have an ASP site where I read two dates from two fields.
The dates are generated using JavaScript and one of the two dates I need to read pass but the other doesn't. Even though they are made the exact same way.
So as you see here from my Immediate Window:
datepicker_start.Value
"03/10/2016"
datepicker_end.Value
"03/23/2016"
The first one parses fine, the second one does not:
DateTime start = DateTime.Parse(datepicker_start.Value);
DateTime end = DateTime.Parse(datepicker_end.Value);
It throws a FormatException on the end date:
DateTime.Parse(datepicker_end.Value)
threw an exception of type
System.FormatException: The String wasn't recognized as a valid
DateTime.
I cannot understand why this is happening. If you need anything other than what I gave already please let me know as this is truly puzzling.
DateTime.Parse uses standard date and time format of your current culture settings.
Probably your culture setting has dd/MM/yyyy as a standard format and since there is no 23rd month, your second line throws FormatException.
I would suggest to use DateTime.ParseExact with a custom format like;
DateTime end = DateTime.ParseExact(datepicker_end.Value,
"MM/dd/yyyy",
CultureInfo.InvariantCulture);
For example; if you debug your code, your start will be 3rd of October, not 10th of March.

Winforms C# Date in TextBox changes month and day

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.

WPF Datepicker - SelectedDate just date and not time

I know this may be a duplicate but using the .NET framework I can't seem to get the date and not the time for a WPF DatePicker.
I have this:
DatePicker.SelectedDate.Value.Date
I believed using the "Date" property would only return the date, but it returns the time "12:00:00" as well.
I read https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date so I'm not sure what I am doing wrong.
I'm sure it's something silly as always, but with no helpful eye with me to tell me, I thought I resort to SO!
DatePicker.SelectedDate.Value.Date is a DateTime Nullable property. So any DateTime Property has the date and time section. but in this case it is not fill with the correct value and it will gives you the default value. if you want to get the date only use following code,
DatePicker.SelectedDate.Value.Date.ToShortDateString()
SelectedDate property is of type Nullable<DateTime> it gives you the date however the time is reset as 12:00:00 midnight (00:00:00)
see more on DatePicker.SelectedDate Property
from MSDN: DateTime.Date Property
The value of the Kind property of the returned DateTime value is the same as that of the current instance.
Because the DateTime type represents both dates and times in a single type, it is important to avoid misinterpreting a date returned by the Date property as a date and time. For more information, see "Saving and Restoring DateTime Values" in the DateTime topic.
While selecting the date from the datepicker in you code you can do following:
DateTime from = From_Date_Picker.SelectedDate.Value.Date
The following example uses the Date property to extract the date component of a DateTime value with its time component set to zero (or 0:00:00, or midnight). It also illustrates that, depending on the format string used when displaying the DateTime value, the time component can continue to appear in formatted output.
That says that depending on the Format (in this case the DatePicker i think) the Time component can appear. Like in your link, the Output is 12:00 AM
So Check the Format / properties of the DatePicker.
in your code, you can do the following:
string shortDate = datePicker.SelectedDate.Value.ToShortDateString();
or, if you'd like to specify the format of the date:
string formatDate = datePicker.SelectedDate.Value.ToString("yyyy-MM-dd");
Here datePicker is object of DatePicker WPF
Check to make sure your Windows regional settings are set to a 24hr clock. I'm guessing its returning 12AM

Got the time of day?

I'm stuck in a hole, and I cannot for the life of me dig myself out of it.
This is a highly aesthetics question, but I like to get what I ask for from my code.
I'm trying to parse a string representing time to a DateTime variable that I then send to a textBox as well as to my LINQ query.
I would like to represent my time in this format: "yyyy-MM-dd hh:mm:ss" and that is what i get from my Select query, but as soon a I try to parse what the user has written in the textBox to DateTime it gives me "1/13/2011 12:00:00 AM", even if it was in the format "2011-01-13 00:00:00".
I feel like I've tried everything to make this work, but there must be a solution, can you guys help me find it? What IFormatProvider am I suppose to use?
This is what i tried:
//textBox1.Text = "2011-01-13 00:00:00";
DateTime = TimeFrom;
TimeFrom = DateTime.ParseExact(textBox1.Text, "yyyy-MM-dd hh:mm:ss", null);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"), DateTimeStyles.None);
TimeFrom = DateTime.ParseExact(textBox1.Text, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), new CultureInfo("sv-SE"),System.Globalization.DateTimeStyles.AssumeUniversal);
TimeFrom = DateTime.ParseExact("2008-10-01 16:44:12.000", "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.CreateSpecificCulture("en-US"));
textBox1.Text = TimeFrom.ToString();
But none of it gives me the formatting that I so crave.
UPDATE:
It appears that somehow the Current Culture got changed from the time I declared my DateTime variable to the time I wanted to Parse the textBox1.Text value from "sv-SE" to "en-EN" which is why it decided to change the way my time was formatted. It is not something I'm doing in my code. Any ideas as to why?
Why it decided to ignore my (IFormatProvider) new CultureInfo("sv-SE",true), is something I haven't figured out yet ether.
If you have any suggestions, please let me know.
textBox1.Text = TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
or something like:
textBox1.Text = TimeFrom.ToString(new CultureInfo("sv-SE"));
depending on what you need exactly.
Parsing means to take a string and turn it into a strongly-typed DateTime object, using a format.
To turn that strongly-typed DateTime object into a string, you call ToString using a format.
TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
Edit: Maybe you just need to set the Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE") before you start doing stuff. Is this an ASP.NET app?
Have you tried
TimeFrom.ToString("yyyy-MM-dd hh:mm:ss");
You need to format DateTime only when you convert it to String.
Have you tried InvariantCulture? To print out the string in a certain format take a look at format strings
Hey guys. I just wanted to go public with what caused my problems.
What happened was that when I rendered a report and loaded it into a report viewer the CurrentCulture got changed to en-EN. The report language was set to blank which leads me to believe that the default language is en-EN.
This then changed the way that my time was represented. A DateTime variable does not remember its formatting culture. So any changes in representing a DateTime as a string has to contain the string formatting, like this: dateTimeVariable.toString("yyyy-MM-dd hh:mm:ss")
I hope someone will find this helpfull.

Categories