Add the current time to a DateTime?

2019-04-10 10:36发布

问题:

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

回答1:

 string s = "27.08.2010";
 DateTime dt = DateTime.ParseExact(s, "dd.MM.yyyy", CultureInfo.InvariantCulture);
 DateTime result = dt.Add(DateTime.Now.TimeOfDay);


回答2:

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;