0

I have a string Date which is coming from Database I need to parse or convert that String Date in DateTime form. Sharing the data and code as of now sharing the date which is coming from DB

String Date="7/19/2010 7:34:43 AM";

// I am parsing in DateTime form by below code

Date= DateTime.Parse(Date).ToString("yyyy-MM-dd HH:mm:ss.fff");

But I am getting the error while parsing with existing code as String was not recognized as a valid DateTime. Can anyone please share some info how can I resolve this error so that I wont receive any exception

Note

Issue with my code is the date which is coming from Database is not a valid string type that's why I am getting the error string is not recognized as valid datetime

2
  • are you trying this "Date= DateTime.Parse(Date).ToString("yyyy-MM-dd HH:mm:ss.fff");" in code behind ? Commented Jul 1, 2014 at 5:49
  • yes Krunal It is existing code when I debugged I found it is failing Commented Jul 1, 2014 at 5:52

3 Answers 3

1

You should do, using DateTime.ParseExact

 DateTime dt = DateTime.ParseExact("7/19/2010 7:34:43 AM",
                            "M/d/yyyy h:mm:ss tt",
                            CultureInfo.InvariantCulture);
Sign up to request clarification or add additional context in comments.

6 Comments

hi Sajeetharan ,thanks for sharing ur code but when I tried ur code I am getting build error Error 102 Cannot implicitly convert type 'System.DateTime' to 'string'
@Rahul Try the modified one
Thanks Sajeetharan now I am not getting error but I don't want to change the variable name I want to use the existing variable only
@rahul then just replace the variable, your history shows you dont accept answers, try to appreciate those who help you!
String Date = "7/19/2010 7:34:43 AM"; Date = DateTime.ParseExact(Date,"M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); When I am using I am getting error like cannot convert datetime to system.string and also I am not getting the time details for ex 7 Hours 34 Min 40 Sec AM
|
0

DateTime.ParseExact(yourstring, "yyyyMMdd_HH:mm:ss.fff", new CultureInfo("en-US"));

Will solve your issue.

For reference follow :

Date Time Parse

Date Time Parse Exact

Comments

0

Either you can use

DateTime.ParseExact or DateTime.TryParseExact

This will allow you to specify specific formats. I prefer the TryParseExact as they provide good coding style for the casing error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.