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

how to convert this string " 1-Jan-2014 at 16:18 " to valid date time
Posted

Hi Sadhana,

Please see the below links for string to datetime conversion. Hope this will help you.

Easy String to DateTime, DateTime to String and Formatting[^]

http://msdn.microsoft.com/en-IN/library/cc165448.aspx[^]
 
Share this answer
 
Comments
sadhana4 24-Jul-14 2:18am    
i m trying converting my date example
BASICDATETIMEOFINVOICE = "1-Jan-2014";

DateTime date;
date = new DateTime();
date = DateTime.ParseExact(BASICDATETIMEOFINVOICE, "dd-MM-yyyy", null);

but it is given error
String was not recognized as a valid DateTime.
sadhana4 24-Jul-14 2:19am    
why
Sharmanuj 24-Jul-14 3:00am    
Hi Sadhna,

please see the below solution provided.
Let me answer your comment first. For that modify code like this:
C#
BASICDATETIMEOFINVOICE = "1-Jan-2014";
DateTime date = DateTime.ParseExact(BASICDATETIMEOFINVOICE, "d-MMM-yyyy", CultureInfo.InvariantCulture);

And for your question,code should go like this:
C#
DateTime date =DateTime.ParseExact("1-Jan-2014 16:18","d-MMM-yyyy HH:mm",CultureInfo.InvariantCulture);

Important to refer : http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx[^]

Regards..
 
Share this answer
 
v2
Comments
sadhana4 30-Jul-14 1:47am    
i put this :
BASICDATETIMEOFINVOICE = "1-Mar-2014";
DateTime date = DateTime.ParseExact(BASICDATETIMEOFINVOICE, "d-MMM-yyyy", CultureInfo.InvariantCulture);

date = "3/1/2014 12:00:00 AM"
month is coming first and date is second
Thanks7872 30-Jul-14 1:51am    
date is of type DateTime which doesn't have any format. To get it in required format you can use .ToString("Your required format");.
sadhana4 30-Jul-14 1:56am    
it is working find
i convert date.ToString("yyyy/MM/dd");
so it is showing correct
Thanks7872 30-Jul-14 2:02am    
Its always good to accept answers that worked for you so in future some one facing same issue may come to know.
Use this code

string myDate = "02-Mar-2014";
DateTime myDateTime;
myDateTime = Convert.ToDateTime(myDate);
string newDate = myDateTime.ToString("mm/yyyy/dd");
MessageBox.Show(newDate);
 
Share this answer
 
Comments
Thanks7872 24-Jul-14 2:44am    
Don't repost solutions. Update your first solution.Remove this.

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