Set a specific date to a datetimepicker in c#

159 views Asked by At

I have a date coming from a database as a string. I want to set it to a datetimepicker.

The problem is, it can be in many formats, such as:

d/m/yyyy
d/mm/yyyy
dd/m/yyyy
dd/mm/yyyy

I don't know how to do it.

If I can convert this to something like dd/mm/yyyy I can show it in datetime picker.

How can I do this programmatically ?

1

There are 1 answers

0
voytek On

You can parse it like that:

    string inputStringDate = "01/01/2001";
    DateTime outputDateTime;
    string[] formats = { "d/M/yyyy", "d/MM/yyyy", "dd/m/yyyy", "dd/mm/yyyy" };
    if (DateTime.TryParseExact(inputStringDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out outputDateTime))
    {
        //There you have your DateTime in outputDateTime var
    }