Question

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?

Was it helpful?

Solution

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

OTHER TIPS

First you need to parse with DateTime.Parse what you read from command line.

Then, you can do that using DateTime.Now.TimeOfDay like;

DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;

You could do

closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);

Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.

There are other options, including to parse the date, as you do, and then add TimeOfDay to it.

DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;

You can do this:

closeDate = DateTime.Parse(Console.ReadLine())
    .Add(DateTime.Now - DateTime.Today);
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);

Well how about this little function:

public static DateTime ChangeTime(DateTime dateTime)
{
    return new DateTime(
        dateTime.Year,
        dateTime.Month,
        dateTime.Day,
        DateTime.Now.Hour,
        DateTime.Now.Minute,
        DateTime.Now.Second,
        DateTime.Now.Millisecond,
        DateTime.Now.Kind);
}

This is a possible solution:

store DateTime.Now in a variable

var date = DateTime.Now;

Then u can access the Hours, Minutes and Seconds like this:

date.Hour;
date.Minute;
date.Second;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top