How can I setup DateTime hour,minute and second?

user1281566 picture user1281566 · Mar 19, 2013 · Viewed 8.2k times · Source
private void StartAuction()
{
    DateTime closeDate;
    closeDate = DateTime.Parse(Console.ReadLine());
}

I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.

Any suggestions?

Answer

Jon Skeet picture Jon Skeet · Mar 19, 2013

Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:

private void StartAuction()
{
    DateTime closeDate = DateTime.Parse(Console.ReadLine());
    DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
    ...
}

(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)

As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)