Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add the current time to a DateTime?

I have a string which represents a date, its given back from a DropDownList. The string is "27.08.2010" for example. Now I want to add the current time to this and parse it to Datetime ... so in the end it should be a DateTime like 27.08.2010 15:12:45 for example.

How could I do this? Right now, I am putting together a string using DateTime.Now.Hour etc. and make a DateTime out of it, but that seems to be the wrong way.

Thanks :)

like image 535
grady Avatar asked Aug 27 '10 07:08

grady


2 Answers

 string s = "27.08.2010";
 DateTime dt = DateTime.ParseExact(s, "dd.MM.yyyy", CultureInfo.InvariantCulture);
 DateTime result = dt.Add(DateTime.Now.TimeOfDay);
like image 165
Dmitry Ornatsky Avatar answered Oct 08 '22 00:10

Dmitry Ornatsky


You can parse the string into a DateTime instance then just add DateTime.Now.TimeOfDay to that DateTime instance.

  DateTime date = DateTime.ParseExact("27.08.2010", "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
  TimeSpan time = DateTime.Now.TimeOfDay;
  DateTime datetime = date + time;
like image 24
Chris Taylor Avatar answered Oct 07 '22 22:10

Chris Taylor