Click here to Skip to main content
15,891,687 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a problem converting string to datetime.
string datestr="14/2/2015";
DateTime x1;
                        string pattern = "dd-MM-yyyy";
                        DateTime.TryParseExact(EndDate, pattern, null, DateTimeStyles.None, out x1);
                        DateTime.TryParse(EndDate, out x1);
                        DateTime.TryParseExact(EndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out x1);
output like this 1/1/0001 12:00:00 AM

if I am using x1 = Convert.ToDateTime(datestr); 
I got exception.


please help me
Thanks
Posted

help you with what exactely ? do you want this :
C#
x1 = Convert.ToDateTime(datestr); 
to work properly ? then you have to read this https://msdn.microsoft.com/en-us/library/9xk1h71t(v=vs.100).aspx[^] and pay attention to " If provider is null, the DateTimeFormatInfo for the current culture is used."

Given what you've supplied, it would appear as if "14/2/2015" isn't correct for your current culture setting - I'd try this first

string datestr="14/2/2015";
CultureInfo culture = new CultureInfo("en-GB");
DateTime x1 = Convert.ToDateTime(datestr,culture );


and if that works you know your culture setting is likely 'en-US' or something else (in which case of 'en-US' the string should be formatted "2/14/2015")
 
Share this answer
 
v2
Because your default culture format is en-US
C#
string datestr="14/2/2015";

It's mean: MM/dd/YYYY
Program detect:
C#
Month = 14
Day = 2
Year = 2015

=> so you should change as:
1/
C#
string datestr="02/14/2015";
DateTime dt = Convert.ToDateTime(datestr);

Hope this help!
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 14-Feb-15 3:26am    
None of the formats is wrong or right. It depends on culture and/or format string. This "answer" is misleading. If you used to use certain culture, it does not mean others do the same.
—SA
Thanh Xuan Vu 14-Feb-15 4:24am    
Yes i've updated this answer.I'm using culture is EN.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900