6

In C# / Winform, I'm able to parse a string to a date if the user input: dd/mm/yyyy

DateTime.Parse(date).ToString();

I would like to be able to parse without the slash (like in a datagridview or a DateTimePicker for example).

01022012 should be parsed to 01/02/2012

Anyone know how to parse it with DateTime.Parse?

Here is my code :

    private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
        {
            string date = Convert.ToString(e.FormattedValue).Trim();

            if (date.Length > 0)
            {
                try
                {
                    DateTime _date;
                    DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
                    date = _date.ToShortDateString();
                    dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
                }
                catch
                {
                   MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   e.Cancel = true;
                }
            }
        }

    }

Here is the Exception Message :

enter image description here

It says that : "System.FormatException: The string is not recognized as a DateTime valide"

Walter Fabio Simoni
  • 5,671
  • 15
  • 55
  • 80
  • @Sander While i'm sure this question has been answered on Stackoverflow before, i cannot find any with a quick search. And that [linked question](http://stackoverflow.com/questions/5793163/c-sharp-winforms-datetimepicker-custom-format) would in no way help Walter. – Ian Boyd Jun 27 '13 at 13:36
  • Why is your question tagged json, how is json is invloved? If you are trying to parse out a json response there are MUCH easier ways to do it then parsing our each part by hand. – Scott Chamberlain Jun 27 '13 at 13:36

3 Answers3

16

Try with something like this...

string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, date);

... and, with date variable, you only need to...

string slashedValue = date.ToString("dd/MM/yyyy");
HuorSwords
  • 2,225
  • 1
  • 21
  • 34
  • 1
    Suggestion to the OP: use the `TryParseExact` method to avoid the `FormatException` – NominSim Jun 27 '13 at 13:36
  • Nice! Updated with your suggestion! – HuorSwords Jun 27 '13 at 13:37
  • I tried your tips and the forma is OK ! But, i don't know why, i have a FormatException on my DataGrid. In fact, i use this code in order to check if the data inputted is a date. I edited my code. Have you some ideas please ? Thanks – Walter Fabio Simoni Jun 27 '13 at 13:56
  • What is the exact message of this `FormatException`? It helps us to figure out what are you doing... – HuorSwords Jun 27 '13 at 14:12
  • "System.FormatException : The string is not recognized as a dateTime valide" (It's a DataGridView Exception). I edited my post with the screenshot. – Walter Fabio Simoni Jun 27 '13 at 14:17
  • It's possible that is related to a problem with the order of day and month in your date string. Please, try to set the values: `"01012013"` and `"01312013"`. Are you reproducing the problem? – HuorSwords Jun 27 '13 at 14:26
  • Yes i'm reproducing the problem. It appear to be related to the DatagriView. Is there a way to tell that a cell is a DateTime, in order to having the auto-formatting ? – Walter Fabio Simoni Jun 27 '13 at 14:29
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/32502/discussion-between-huorswords-and-walter-fabio-simoni) – HuorSwords Jun 27 '13 at 14:40
3

HuorSwords isn't wrong (other than the use of string as the input value), but the answer doesn't strictly answer the question: in order to display the date as requested, you need to format to a string after the fact:

DateTime date = DateTime.ParseExact(input, 
  "ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");
Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
0

That seems like an awful lot of work when you could do something as simple as the two examples below. Date and time can be formatted using predefined formats and also user-defined formats. This is a link to a brief video demonstrating both uses from a text editing program I'm designing. https://od.lk/s/MTRfMjY2NzQxODVf/2022-03-20-20-55-52.mp4

This link will certainly get you on the right track: https://www.vbtutor.net/vb2008/vb2008_lesson16.html

'Declaration (If you wish to use SpeechSynthesizer)
Private Ethro As SpeechSynthesizer = New SpeechSynthesizer()

Ethro.SpeakAsync(Format(Now, "Long Date"))

'Or a simple MsgBox:
        MsgBox(Format(Now, "Long Date"))