Click here to Skip to main content
15,917,642 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
want to convert string into date time.when the day is geater then 12 it gives execption that "input wase not in correct format". pleasr help me out

C#
string Date="30/05/2014";

 if (Date != null)
                {
                    string returnDate = DateTime.Parse(Date).ToString("yyyy/MM/dd");// Error on this line when day is greater than 12
                    return Convert.ToDateTime(returnDate);
                }
                else
                {
                    return DateTime.Now;
                }
Posted
Updated 16-Jun-14 0:00am
v2

DateTime.ParseExact[^] Or DateTime.TryParseExact[^]
C#
string returnDate = DateTime.ParseExact(Date, "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");


Why you call convert DateTime to string and again convert back to DateTime?
You can use one of the above method to convert string to DateTime. No need to convert it back to string and then again to a DateTime. You need to understand that DateTime structure hold only the value and there is no display format. when we need to display it in any format we can call ToString or string.Format methods to convert it to a string with given format.
 
Share this answer
 
v4
Refer String was not recognized as a valid DateTime.[^] to understand why exactly this issue occur and how to resolve.
 
Share this answer
 
Try
C#
DateTime.ParseExact(Date, ("yyyy/MM/dd", CultureInfo.InvariantCulture);
 
Share this answer
 
try this
DateTime dt;
DateTime.TryParseExact(dateTime, 
                       "yyyy/MM/dd", 
                       CultureInfo.InvariantCulture, 
                       DateTimeStyles.None, 
                       out dt);
 
Share this answer
 
Use DateTime.ParseExact[^] for that...
C#
DateTime.ParseExact("30/05/2014", "dd/MM/yyyy", CultureInfo.InvariantCulture);
 
Share this answer
 
Comments
fak_farrukh 16-Jun-14 6:04am    
i want to convert into "yyyy/MM/dd" this format
Thanks7872 16-Jun-14 7:25am    
Datetime doesn't have format. If you want specific format,that is the string which represents the date in specific format.

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