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 :
It says that : "System.FormatException: The string is not recognized as a DateTime valide"
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.
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).
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With