Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a string to a date without slashes

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"

like image 575
Walter Fabio Simoni Avatar asked Jun 27 '13 13:06

Walter Fabio Simoni


People also ask

How do you write dates without slashes?

Select the date cells you will remove the dashes, slashes, or hyphens from, right click, and select Format Cells from the context menu. 2. In the Format Cells dialog, under the Number tab, click to activate Custom in the Category list box, type the date code mmddyyyy into the Type box, and click the OK button.

How do you parse a string to a date?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).


1 Answers

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");
like image 181
HuorSwords Avatar answered Oct 13 '22 11:10

HuorSwords