views:

34

answers:

2

I have a timepicker (datetimepicker) formatted as HH:mm - 24 hour clock. It displays as 00 to 24 and 00 to 59 and will not allow invalid values to be entered. This is exactly what I want.

However, it returns values as 12 hours with AM and PM indicators. This means that when the user enters "00" it is returned as "12", and "14" is returned as "2:00". This is NOT what I want.

I can test for and convert these unwanted return values, but surely(?) there is a more elegant way of persuading this thing to give me the values I want rather than checking for these special conditions? Some simple property that I've overlooked perhaps?

+1  A: 

How are you getting hold of the entered time value from the control?

If you have a DateTimePicker control and set its Format property to Custom, and its CustomFormat property to HH:mm, you get a 24 hour format time (as a DateTime type) when you read the Value property.

EDIT: If you are using the ToString() value (as you say in the above comment), this will be using your current localisation settings. You would be much better of reading the values from the DateTime (ie. DateTime.Hour DateTime.Minute).

adrianbanks
+1  A: 

When you read the value, you'll need to use:

string value = dateTimePicker.Value.ToString("HH:mm");

If you just use Value.ToString(), you'll get the default (12 hour) string formatting.

Reed Copsey
This is exactly what I am doing (i.e., value.ToString() rather than value.ToString(formatting). I would have thought that setting the format for the control would have already done this for me, but apparently not. Thanks - I will try this when I get back to work Monday AM
mickeyf
@mickey: ToString() will just use the current culture - it's unrelated to the control, since it's just calling DateTime.ToString. You're getting a DateTime instance back when you call picker.Value. You can override the current culture, and set hte current culture to 24time, and ToString() will give you the behavior you were expecting.
Reed Copsey
Thank you - this exactly solves the problem. Apparently the Format property for the control means "Strictly the display format for the control itself", which is reasonable enough, but was not how I was thinking of it.
mickeyf