Reputation: 4359
I’m using C# and WinForms to try and put just the date from a dateTimePicker into a variable. But I keep getting the date and the time. In the example below textBox1 shows what I’m looking for. But I can’t figure out how to do the same for textBox2. Where it gives the date and time. This isn’t the exact code I’m using in my app, but a simplified example of it for use as an example. How can I modify it to do what I need? Thanks.
private void dateTimePicker1_CloseUp(object sender, EventArgs e)
{
DateTime varDate;
textBox1.Text = dateTimePicker1.Value.ToShortDateString();
varDate = dateTimePicker1.Value;
textBox2.Text = Convert.ToString(varDate);
}
Upvotes: 4
Views: 18317
Reputation: 4807
Try this
textBox2.Text = varDate.ToShortDateString();
or
varDate = DateTimePicker1.Value.Date;
textBox2.Text = varDate.ToShortDateString() // varDate.ToString("MM/dd/yy") this would also work
Upvotes: 4
Reputation: 1423
Try this :
textBox1.Text = dateTimePicker1.Value.ToString("yyyy-MM-dd");
Upvotes: 1
Reputation: 28617
Thanks to Lazarus' comment above I think I understand your question now...
There is no way for a DateTime variable to only hold a Date value, the best you can do is set the time part to 00:00:00. Unfortunately this will not stop it being printed out when you call the default ToString() method. Therefore the method to solve your issue will entirely depend on what the actual problem you are trying to solve is:
If you are trying to display only the Date part in a TextBox then you can use the ToShortDateString() method, or any other date formatting string, but I guess you already know this, since you are using that method with TextBox1.
If you are trying to compare two datetimes and don't want the time part to be relevant you can use the Date property to ensure that the time part is set to midnight.
datetimeA.Date == dateTimeB.Date
Note that this doesn't avoid the comparison of the time part (the objects being compared are still Datetimes, but it does ensure that they are equal.
The only other reason that I can think you may wish to do this is because you feel that the object is too complicated and contains extraneous information. While I very much doubt this is the issue it may comfort you to know that the internals of a DateTime object are little more than a single long value, and you are not wasting space with the unused time portion.
Upvotes: 1
Reputation: 24385
Like this:
private void dateTimePicker1_CloseUp(object sender, EventArgs e)
{
DateTime varDate;
textBox1.Text = dateTimePicker1.Value.ToShortDateString();
varDate = dateTimePicker1.Value;
textBox2.Text = varDate.ToShortDateString();
}
Upvotes: 1
Reputation: 292535
varDate = dateTimePicker1.Value.Date;
This will return the DateTimePicker's value with the time set to 00:00:00
Upvotes: 10