Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
HI,

We need to convert a string value(2016/02/22) to DATETIME OR DATE with 8 characters means the value should be in (yyyyMMdd) with Date varable.

The Format of the Date value should be 8 characters.When we tried to convert the string to Date "
C#
String was not recognized as a valid DateTime

",error occuring.

What I have tried:

We need to convert a string value(2016/02/22) to DATETIME OR DATE with 8 characters means the value should be in (yyyyMMdd) with Date varable.

The Format of the Date value should be 8 characters.When we tried to convert the string to Date "
C#
String was not recognized as a valid DateTime

",error occuring.
Posted
Updated 29-Feb-16 3:27am

1 solution

Try with below code with ParseExact:
C#
string timeStr = "2016/02/22";
DateTime dtObject = DateTime.ParseExact(timeStr, "yyyy/MM/dd", CultureInfo.InvariantCulture);

Follow below link that may help you:

Different Ways to Parse string to DateTime Object in C#[^]
 
Share this answer
 
Comments
Member 11658469 29-Feb-16 9:45am    
Thanks for the reply.

We need the date value length should be 8 characters.For the above value 10 characters will be there.Please adivce to restrict the length to 8 characters.
[no name] 29-Feb-16 9:55am    
You can use like below:

string timeStr = "20160222";
DateTime dtObject = DateTime.ParseExact(timeStr, "yyyyMMdd", CultureInfo.InvariantCulture);
Member 11658469 29-Feb-16 10:30am    
Hi,

We tried this one also,same result we are getting.The Output will be "2/22/2016".This one also contains 10 character length.
[no name] 29-Feb-16 10:57am    
If you trying to make it as 8 characters with DateTime object, then it won't. So you can use datetime object to string like:

string timeStr = DateTime.Now.ToString("yyyyMMdd");
Member 11658469 1-Mar-16 0:09am    
Hi,

This string conversion we know,but the thing is we need to pass the variable in Date Data type.There we face the issue.

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