Asynchronous Asynchronous - 4 months ago 32
C# Question

Converting String (Textbox.text) to DateTime with current time

I am trying to convert this e.g. 12/31/2012 format into DateTime, however when I run this code the conversion works but the time is not current. I am looking to convert to DateTime but with the current time:

Example: When I run the below code and enter date: 12/31/2012

I get: 12/31/2012 12:00:00 AM

I am not sure how to get the current time instead of 12:00:00 AM

Console.Write("Enter Current Date: ");

string strMyDate = Console.ReadLine();

DateTime dt = DateTime.Parse(strMyDate);




You can extract only the time from DateTime.Now by using the TimeOfDay property and add it to your manually entered date, e.g.

var time = dt.Add(DateTime.Now.TimeOfDay);

As an additional note, I would use DateTime.TryParse instead, as the value entered by the user may not be a parseable date, e.g.

DateTime dt;
var isDate = DateTime.TryParse(strMyDate, out dt);
   var time = dt.Add(DateTime.Now.TimeOfDay);