Click here to Skip to main content
15,908,115 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am trying to get datetime from string, the date time i need must either be in military format ( 24 Hour example 1:30 PM should be 13:30 ) or has PM ,AM indication
this link has not helped me
//https://msdn.microsoft.com/en-us/library/5ey6h79d%28v=vs.110%29.aspx

i tried this
C#
System.DateTime dt = new System.DateTime();
dt = Convert.ToDateTime("01/08/2008 4:50:50.42");//<---- error here
MessageBox.Show(dt.ToString());


What I have tried:

DateTime date1 = new DateTime(int.Parse("2009"),
int.Parse("8"),
int.Parse("1"),
int.Parse("0"),
int.Parse("0"),
int.Parse("0")
);
i think it is not possible to insert AM or PM as a last parametr in the above code
Posted
Updated 2-Mar-16 11:31am
v4
Comments
Aria Jafarian 2-Mar-16 17:27pm    
You have to use DateTime.ParseExact as indicated below

whats wrong with

C#
string dateString = "01/01/2008 4:50:50.42"; 
string format = "dd/MM/yyyy h:mm:ss.ff";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);


? you can follow here for the specifiers - 'tt' for example is AM/PM ... Custom Date and Time Format Strings[^]
 
Share this answer
 
Comments
Engineer khalid 2-Mar-16 17:45pm    
Hellow Garth.
my computer is set to Arabic calender not Gregorian, most likley this was the error

this is what i have got
Specified time is not supported in this calendar. It should be between 04/30/1900 00:00:00 (Gregorian date) and 05/13/2029 23:59:59 (Gregorian date), inclusive.
//
i will try in another computer , and your answer shall be accepted many thanks
Garth J Lancaster 2-Mar-16 18:22pm    
cool - dont forget you can also change this [CultureInfo.InvariantCulture] to something appropriate
Your code does not produce any error with my localisation

This code will produce AM/PM in the output
C#
MessageBox.Show(dt.ToString("dd/MM/yyyy HH:m:s tt"));

But if you are using dates (especially if they are being used in the context of a database) then you should use unambiguous date formats

e.g.
C#
System.DateTime dt = new System.DateTime();
dt = Convert.ToDateTime("2008-08-01 4:50:50.42");
MessageBox.Show(dt.ToString("yyyyMMddTHH:00:00tt"));

which produces
20080801T04:00:00AM
 
Share this answer
 

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