Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try with this code, but its return error. I can use toString() method, but i want that result been in DateTime



C#
DateTime dt = DateTime.ParseExact("2015.05.05", "MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);
Posted

The problem is that the format string 'MM-dd-yyyy' does not fir to the value '2015.05.05' and for that ParseExact will throw an exception of invalid value... You may try TryParseExact, but the only thin you will get, that no exception will be thrown, but a boolean value will be returned - but still no valid DateTime object...
What you have to do is do it in two steps...
1. Turn string into valid DateTime object according its format:
C#
DateTime oDT = DateTime.ParseExact("2015.05.05", "yyyy.MM.dd", System.Globalization.CultureInfo.InvariantCulture);

2. Format that DateTime object according your needs:
C#
string szDT = oDT.ToString("MM-dd-yyyy");


https://dotnetfiddle.net/VJ61Nu[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 10-May-15 11:01am    
5ed. amazingly, this is the only non-nonsense answer so far. :-)
—SA
Kornfeld Eliyahu Peter 10-May-15 11:06am    
Thank you...
Hi,

check here https://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx[^]

You can code like this also
C#
DateTime dt = new DateTime(2015, 05, 05);
DateTime result = DateTime.ParseExact(dt.ToString("MMM/dd/yyyy"), "MM/dd/yyyy", CultureInfo.InvariantCulture);


If this solves your problem, then please mark it as answer. :-)
 
Share this answer
 
v4

What about String.Replace? Something like:


C#
string str1 = "2015.05.05";
string str2 = str1.Replace(".", "-");
 
Share this answer
 

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