Click here to Skip to main content
15,884,836 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I get output as string "01-01-2013 00:00:00" now i want to convert into date

i used following format

row[colNum - 1] = temp.ToString();
DateTime d = DateTime.Parse(temp.ToString());   // giving me error
DateTime conv = DateTime.FromOADate(d);
string convT = d.ToString("dd/MM/yyyy");
convT = convT.Replace("-", "/");


Error: Giving input string is invalid format

What I have tried:

i tried following code also

DateTime d = DateTime.ParseExact(temp.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
Posted
Updated 28-Jun-23 10:26am

The following code works.

The convert to Double (commented out) does not work.
C#
string temp = "01-01-2013 00:00:00";
	DateTime d = DateTime.Parse(temp.ToString());   // giving me error
 	//DateTime conv = DateTime.FromOADate(d);
	string convT = d.ToString("dd/MM/yyyy");
	convT = convT.Replace("-", "/");
	Console.WriteLine(convT);


The output is:

01/01/2013


Also, the line
convT = convT.Replace("-", "/");
does not do anything. It's attempting to replace - with / and there are no dashes in the string.

Maybe you meant:

C#
string temp = "01-01-2013 00:00:00";
	DateTime d = DateTime.Parse(temp.ToString());   // giving me error
 	//DateTime conv = DateTime.FromOADate(d);
	string convT = d.ToString("dd/MM/yyyy");
	Console.WriteLine(convT);
	convT = convT.Replace("/", "-");
	Console.WriteLine(convT);


Output is:
01/01/2013
01-01-2013



If Parse is throwing an exception, it is likely that the string is not in any of numerous formats that Parse can deal with.
 
Share this answer
 
v3
TryParseExact is the way to go rather than Parse or ParseExact, but your format string doesn't match the date example you show:
string temp = "01-01-2013 00:00:00";
DateTime d = DateTime.ParseExact(temp.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

Compare the two and you'll see what I mean:
01-01-2013 00:00:00
MM/dd/yyyy hh:mm:ss tt
Your format specifies a trailing AM/PM indicator which the date data does not provide.

Have a look here: Formatting a DateTime for display - format string description[^] - the format codes are the same for parsing.
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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