Reputation: 3
Alright, so I have 2 DateTimePickers with custom formats that are set when the form loads,
start.Format = DateTimePickerFormat.Custom;
end.Format = DateTimePickerFormat.Custom;
start.CustomFormat = "dd/MM/yyyy";
end.CustomFormat = "dd/MM/yyyy";
And, my code is supposed to get all weeks between these dates, which it does correctly, then print every week. I'm managing to do it this way:
DateTimePicker tempdt = start;
tempdt.Format = DateTimePickerFormat.Custom;
tempdt.CustomFormat="dd/MM/yyyy";
int a = getWeeks();//method that gets the weeks between start and end
int d = 0;
for (int i = 0; i < a; i++)
{
d += 7;
MessageBox.Show(tempdt.Value.Date.AddDays(d).ToShortDateString());
}
The code works perfectly, and it does get the weeks precisely, however tempdt still seems to have a "mm/dd/yyyy" format.
Any idea what I might be missing?
Upvotes: 0
Views: 201
Reputation: 54487
The point of the format of a DateTimePicker is to control what the user sees in the control. That 'tempdt' is not even being shown to the user at all so should not be being used at all. Your calculations are using the Value property of that DTP. That property is a DateTime and is completely unaware and unaffected by the format of the DTP. Get rid of the DTP in the calculation and just use a DateTime.
When you display the results of the calculation, you have to convert that DateTime to a String in the appropriate format at that time. If you want to display "dd/MM/yyyy" format then call .ToString("dd/MM/yyyy") rather than .ToShortDateString() because the latter will use the default system format.
Upvotes: 1
Reputation: 127603
The DateTimePickers have nothing to do with this. Your issue is you call ToShortDateString()
which for your current culture is set to display as mm/dd/yyyy
.
Just use your custom format in the text box too.
MessageBox.Show(tempdt.Value.Date.AddDays(d).ToString("dd/MM/yyyy"));
Also from the code you have shown tempdt
is completely unnecessary and it is never even shown to the user. You can also remove the Date
call as you don't display the time anyway to the user and are only adding whole number days to the date. This lets you simplify your code to
int a = getWeeks();//method that gets the weeks between start and end
int d = 0;
for (int i = 0; i < a; i++)
{
d += 7;
MessageBox.Show(start.Value.AddDays(d).ToString("dd/MM/yyyy"));
}
Upvotes: 1