LOGIN    REGISTER    YOUR CART

homepage
VisualHint's blog
2008
Sep19

A suffix for the day of the month in the DateTimePicker

The TimeSpanEditor was able to do it but not the DateTimePicker due to the way DateTime.Parse works. I have changed that and the DateTimePicker is now able to show a different suffix depending on the day of the month. Here is an animated screenshot:

English suffix for the DateTimePicker

To work, you need to handle the ValueChanged event, like this:

private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
    FieldPack fieldPack = (sender as FieldPack);
    Field field = fieldPack.GetField(3);
    if (field != fieldPack.EmptyField)
        SetDayLabel(fieldPack.OwnerEditor as DateTimePicker, field);
}
    
private void SetDayLabel(DateTimePicker dtp, Field field)
{
    if (dtp.Value != null)
    {
        DateTime value = (DateTime)dtp.Value;
        string suffix = "th, ";
        if (value.Day == 1)
            suffix = "st, ";
        else if (value.Day == 2)
            suffix = "nd, ";
        else if (value.Day == 3)
            suffix = "rd, ";

        if (!field.Value.Equals(suffix))
        {
            field.Value = suffix;
            field.OwnerFieldPack.OwnerEditor.RecalcLayout();
        }
    }
}

Depending on your language, you can of course change the prefix. Note that there is no particular requirement for the format string.