Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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);

    Console.WriteLine(dt);

    Console.ReadKey();
like image 526
Asynchronous Avatar asked Nov 21 '25 17:11

Asynchronous


1 Answers

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);
if(isDate)
{
   var time = dt.Add(DateTime.Now.TimeOfDay);
}
like image 113
George Johnston Avatar answered Nov 23 '25 05:11

George Johnston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!