Dashamlav
Dashamlav

Reputation: 245

Can we add date and time values to a DateTime variable separately?

I need to assign Date and Time values to a DateTime variable separately. Is it possible?

I have a DateTime variable named currentDate. I need to assign a Date value to it from a DateTime variable start, and the Time value from another DateTime variable called outTime.

Let's say start has 4/2/2018 10:00:00 as the value stored in it. And, outTime has 4/4/2018 16:00:00 as the value stored in it. Thus, my currentDate value should be 4/2/2018 16:00:00 where you can see that 4/2/2018 came from start and 16:00:00 came from outTime.

I am new to this and I was completely unsure if we could even do this or not.

Edit - Code Snippet

This is how I am doing it. However, I am getting an error on outTime.TimeOfDay which says: Cannot implicitly convert type System.TimeSpan to System.DateTime

currentDate = start.Date;
currentDate = outTime.TimeOfDay;

Upvotes: 2

Views: 6711

Answers (3)

JON
JON

Reputation: 1

You can use something like

DateTime meetingAppt = new DateTime(2018, 4, 4, 16, 0, 0);

You can access to hour only writting

meetingAppt.Hour;
meetingAppt.Minute;

But at the same time create new one and only use to date

meetingAppt.Year;
meetingAppt.Month;
meetingAppt.Day;

It's help you?

Upvotes: 0

Anwar Ul-haq
Anwar Ul-haq

Reputation: 1881

Yes you can. like below

class Program
    {
        static void Main(string[] args)
        {

            DateTime date = new DateTime(2018,04,04);
            DateTime dateandTime = new DateTime(date.Year,date.Month,date.Day , 16,00,00);

            Console.WriteLine(dateandTime);

            Console.ReadLine();
        }
    }

Upvotes: 0

adjan
adjan

Reputation: 13652

How about adding the TimeOfDay part to the Date part using DateTime.Add()?

var date = new DateTime(2018, 1, 5, 20, 0, 0);
var time = new DateTime(2018, 3, 2, 15, 0, 0);

DateTime combined = date.Date.Add(time.TimeOfDay);

Results in

1/5/2018 3:00:00 PM

Upvotes: 2

Related Questions