Convert.ToDateTime() error - c#

I get an error trying to convert a string to DateTime, even though this has always worked before.
This is the procedure I used:
Save a datetime to a text file like this:
DateTime.Now.ToUniversalTime().ToString(); //results in something like this 20.9.2015 10.16.12
On application load up:
string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12"
DateTime d = Convert.ToDateTime(s);
This results in this:
String was not recognized as a valid DateTime.
I have never experienced this problem before I installed Windows 10 and Visual Studio 2015, my previous setup was Windows 7 and Visual Studio 2013. The weird thing is that this also results in the same error:
DateTime d = Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString());
This did work perfectly in my previous setup, any ideas why it does not work any more?
Edit: I do believe that this question is not a duplicate of the question Converting a String to DateTime that Thomas Weller linked to. Because this problem is the result of changes in expected behaviour, see the second example. Also I did find a fix to this, but it is not practical:
string s = DateTime.Now.ToUniversalTime().ToString();
s = s.Substring(0, s.IndexOf(" ")).Replace('.', '/') + s.Substring(s.IndexOf(" ")).Replace('.', ':');
DateTime d = Convert.ToDateTime(s);

This probably does not work anymore due to your regional settings on control panel.
To avoid conflicts with regional settings on target enviroment, use DateTime.TryParseExact:
string s = streamReader.ReadLine(); //the saved string s = "20.09.2015 10.16.12"
DateTime d = DateTime.Now;
DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
Also, if this is your default format and you need this format for entire application, you can set the default culture on your config file.
This code:
Convert.ToDateTime(DateTime.Now.ToUniversalTime().ToString())
Should work on any enviroment, once that DateTime.ToString() and Convert.ToDateTime() without a format provider uses the same DateTimeFormatInfo, unless you are changing your culture between these calls. Note that DateTime.ToString() without format specifier will use General date/time pattern (G), that is based on current culture. And Convert.DateTime without FormatProvider will use current culture too (check these references on MSDN).
My last suggestion is, instead of doing replaces, you can do:
string s = DateTime.Now.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss");

I tried following code in console application, and it worked for me. And check .NETFiddle here
string s = "20.09.2015 10.16.12";
DateTime d;
bool isValid = DateTime.TryParseExact(s, "dd.MM.yyyy HH.mm.ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out d);
Try to understand how TryParseExact works. You can read about TryParseExact and formats here. It return a true if it successfully converts the value, else it returns a false.

Please try with this.
CultureInfo objcul = new CultureInfo("en-GB");
DateTime.ParseExact(ValidFrom.Text,"dd/MM/yyyy", objcul);

Related

Convert.ToDateTime Works in console app but errors out in asp.net

Convert.ToDateTime works in console app,
string a = "18/02/2015";
DateTime aa = Convert.ToDateTime(a);
Errors out in asp.net forms saying string is not righ format,
DateTime aa = Convert.ToDateTime(myTextBox.Text);
It used to work before, but since I got a newly installed server it started giving me this error..
Input string seem same to me "18/02/2015"
Convert.ToDateTime uses DateTime.Parse internally, with the current culture of server. And, the problem is your new server's current culture's DateTime format is different from your string.
You can use DateTime.ParseExact() instead of this.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
DateTime.ParseExact(myTextBox.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Format Exception - string not recognized as a valid DateTime

I have an issue similar to this > Format exception String was not recognized as a valid DateTime
However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString(), #"ddMMyyyy", CultureInfo.InvariantCulture);
I am unclear why.
You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture.
For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM
You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire.
E.g.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);
For more information see the api doc:
http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.
In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), #"ddMMyyyy", CultureInfo.InvariantCulture);
Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.
now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy").
You might be better off testing with a static string like "30041999"

DateTime Parsing .Net 3.5

I have a string in my DB2 database which is physically located in US. I have a column value set to this string '2011-12-31 00:00:00' which indicates year 2011, month december and day 1st of the december.
I'm retrieving this as a string in my client program which is running in UK and the UI is set to local culture(the default). My client program also runs in US as well as in Hongkong with the culture set to the local culture there i.e US and HK respectively.
I'm using the following code for parsing the string into a datetime. I'm not very sure whether this is going to work, and I could't find any good link which points me to that direction. Could you please tell me whether this will work in various cultures, if not why?
string quarterStartDate = "2011-12-01 00:00:00";
DateTime quarterStart;
DateTime.TryParse(quarterStartDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out quarterStart);
return quarterStart;
I have a test which works as per my requirement, but again 'am not too sure whether this will work when the UI is going to run in a different country.
string quarterStarter = "2011-12-01 00:00:00";
DateTime quarterStart;
DateTime.TryParse(quarterStarter,CultureInfo.InvariantCulture,DateTimeStyles.None,out quarterStart);
Assert.IsTrue(quarterStart.Year == 2011);
Assert.IsTrue(quarterStart.Month == 12);
Assert.IsTrue(quarterStart.Day == 1);
I would strongly suggest that as you know the format in advance, you use TryParseExact instead of TryParse:
bool success = DateTime.TryParseExact(quarterStarter, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out quarterStart);
Note that you should check the return value of TryParseExact to check that it's parsed correctly - if you're fine with an exception, just use ParseExact instead.
It's entirely possible that your existing code would work just fine - after all, you're already providing the invariant culture - but specifying the format makes it clearer what you really expect, and also means you'll detect if a value in an unexpected format is provided.
You can use ParseExact to pull the date, for example:
var s = "2011-12-01 00:00:00";
var dt = DateTime.ParseExact(s,"yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
You can set a specific format that does not change with culture.
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-MM-dd hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);

DateTime formats C#

I have a string which needs to be converted and validated to a DateTime. The string is in the following format 'dd.mm.yy'
I am trying to convert it to DateTime using the following
string format = "dd.mm.yy";
date = DateTime.ParseExact(current.Substring(aiRule.AiLength), format,
CultureInfo.InvariantCulture);
but unfortunately this fails.
The question is how to convert a string in the format 'dd.mm.yy' to a DateTime ?
Thank you
mm means "minutes". I suspect you want "dd.MM.yy". See MSDN for more information about custom date and time format strings.
(In particular, read the part about the "yy" specifier and how it chooses which century to use. If you can possibly change the input to use a four digit year, that could save you some problems...)
the string format should be like this....
string Format = "dd.MM.yy"
mm is for showing minutes
MM is for showing months..
I hope it will helps you...
As earlier posts has already pointed out, mm means minutes and MM means months. I ran this test snippet and it works as expected:
string format = "dd.MM.yy";
string date = "27.10.11";
DateTime result;
result = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
I'll tell something "heretical". If dd.MM.yy (with 2 or 4 yy) is the format of your local culture, then you could let the DateTime.Parse (not ParseExact!) do its work without setting it to CultureInfo.InvariantCulture, or perhaps setting it to your local culture like new CultureInfo("it-IT").

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