naouf
naouf

Reputation: 637

How to set DateTimePicker to certain time and keep the customized date?

In windows forms C#, I want to set DateTimePicker to certain time and keep the customized date (any date I select from dateTimePicker) when button is clicked.

for example:

Say we have this date and time: 2015-08-15 08:30:00 I want when I click button the date stays same and the time changes to 11:30:00.

I mean if I select any date from dateTimePicker and then click button, the date remains same and time change to 11:30:00 .

Please help me to achieve this.

I might need to modify the following code to achieve what I want:

private void button1_Click(object sender, EventArgs e)
    {
        dateTimePicker1.Value = DateTime.Today.AddHours(11.5); // shows you  current date and 11:30:00 time


    }


    private void button1_Click(object sender, EventArgs e)
    {
        dateTimePicker1.Value = DateTime.Now; // shows you  current date and time

    }

Upvotes: 4

Views: 1777

Answers (2)

Timmy
Timmy

Reputation: 553

You need set it to a custom format then set the time to what you want

private void button1_Click(object sender, EventArgs e)
{
    DateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm tt";

    DateTimePicker1 .Value = new DateTime(DateTimePicker1.Value.Year, DateTimePicker1.Value.Month, DateTimePicker1.Value.Day, DateTime.Now.Hour, DateTime.Now.Minute, 0);
}

This will retain you whatever Date you have currently set in your datetime picker, and will just update the time since the custome formate forces time into it.

    private void button2_Click(object sender, EventArgs e)
{
    DateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm tt";

    DateTimePicker1.Value = new DateTime(DateTimePicker1.Value.Year, DateTimePicker1.Value.Month, DateTimePicker1.Value.Day, 15, 23, 0);
}

Will retain the date and force the time to 3:23 PM.

Just to note there is also

DateTimePicker1.Value = DateTime.Now; That will set the exact date and time of your current computer.

DateTime.Now.Year Gets current year

DateTime.Now.Month Gets current month

DateTime.Now.Day Gets current day

You can use all these to manipulate your datetime picker how you please.

Upvotes: 1

C. Knight
C. Knight

Reputation: 749

I had to do something similar to this a while ago. I ended up having two datetimepickers next to each other, one for the date and the other for the time. Then on the value changed event of each of them I set the value of both date time pickers appropriately. For instance if I had
dtpDate and dtpTime, then

    private void dtpTime_ValueChanged(object sender, EventArgs 
    {
        dtpDate.Value = dtpDate.Value.Date + dtpTime.Value.TimeOfDay
    }
    private void dtpDate_ValueChanged(object sender, EventArgs 
    {
        dtpTime.Value = dtpDate.Value.Date + dtpTime.Value.TimeOfDay
    }

Upvotes: 2

Related Questions