Click here to Skip to main content
15,892,298 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am getting a datetime value in my datatable as 29/07/2014 6:07:05 PM.But i want to convert datetime value to 29/07/2014 06:07:05 PM. How to convert it?
when i try to convert it using
C#
DateTime.ParseExact(29/07/2014 6:07:05 PM, "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).ToString();

it gives exception : String not recognised as valid datetime
Please help.
Posted
Updated 29-Jul-14 4:22am
v2
Comments
Thanks7872 29-Jul-14 10:24am    
What is the difference between two formats you have stated above?
PIEBALDconsult 29-Jul-14 10:34am    
Two-digit hour?
PIEBALDconsult 29-Jul-14 10:35am    
I sure hope that "in your datatable" it is a DateTime and not a string.
pwavell 30-Jul-14 2:15am    
yes it is datetime and not a string.

Try this:
C#
string a=DateTime.ParseExact("29/07/2014 6:07:05 AM", "dd/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture).ToString("dd/MM/yyyy hh:mm:ss tt");


The exception this was giving to you is because ParseExact expects the format of the string to convert,not the format you want to convert it to. That is done in the ToString method.
 
Share this answer
 
v2
1. I could be blind but there is no difference between the date formats you listed in your first sentence.
2. DateTime.ParseExact() expects a string first and you passed in 29/07/2014 6:07:05 PM, which is not a string. You need to put it in quotes for it to be a string, "29/07/2014 6:07:05 PM"
 
Share this answer
 
Comments
Raje_ 29-Jul-14 10:43am    
Yes there is difference. I could not see too initially. Check hour in both dates one is having one-digit hour "9/07/2014 6:07:05 PM"
and another is having two-digit "29/07/2014 06:07:05 PM". :)
ZurdoDev 29-Jul-14 10:51am    
Wow. Good eyes.
pwavell 30-Jul-14 2:14am    
sorry i forgot to put date in double quotes while posting question but the date is written inside double quotes.my requirement is in whatever format the time comes it should be converted to "hh:mm:ss tt" format.
Pikoh 30-Jul-14 3:40am    
Did you tried my solution?
ZurdoDev 30-Jul-14 7:10am    
OK. You have the code so what is the issue? Your code would work.

DateTime.ParseExact("29/07/2014 6:07:05 PM", "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture).ToString();

http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx

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