Click here to Skip to main content
15,908,172 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I am total new to C#

I have one class its structure is

public class Student_Info
 {
     public String Student_Name;
     public DateTime DateofBirth;


 }



I am assigning values to it like this

Student_Info student = new Student_Info();
           student.Student_Name = "XYZ";
           student.DateofBirth = Convert.ToDateTime("2019-01-01");

           MessageBox.Show(student.Student_Name + " " + student.DateofBirth);



but the output is XYZ 1/1/2019 12:00:00 AM

I want this output XYZ 2019-01-01

I want to remove the time part and but dont want to change it to string

Need help ?

Thanks in advance

What I have tried:

I have tried to convert it into string and extract it is working but not according to my requirement
Posted
Updated 26-Sep-19 7:46am

 
Share this answer
 
Comments
BillWoodruff 26-Sep-19 13:49pm    
If you use DateTime.ToShortDateString, you have no control over output format, and cannot produce the format the OP asks for ... unless the default Culture on the OP's machine happens to be inn the format the OP shows.
To add to what the others say, it's not a good idea to rely on Convert methods, particularly not with DateTime and definitely not with anything that the user will input. Convert throws an exception if the input isn't what it expects, and that generally means your app crashes. Instead, use TryParse or TryParseExact which return a bool success / failure indicator - letting you tell the user there was a problem and letting him re-enter it.
C#
DateTime dt;
if (!DateTime.TryParse(userInputString, out dt))
   {
   ... report problem to user ...
   return;
   }
... you can use the valid DateTime value here.
 
Share this answer
 
Comments
BillWoodruff 30-Sep-19 3:47am    
+5 absurd this is not up-voted !
Do use 'TryParse, as OriginalGriff shows in his solution !

To get the output format you want:

MessageBox.Show(student.Student_Name + " " + student.DateofBirth.ToString("yyyy-MM-dd"));

The "yyyy-MM-dd" parameter to 'ToString is a format string [^], [^] that controls DateTime rendering to the output context.
 
Share this answer
 
v2

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