Reputation: 5729
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"
Upvotes: 7
Views: 8660
Reputation: 1
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"))
Upvotes: 0
Reputation: 2245
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");
Upvotes: 17
Reputation: 45058
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");
Upvotes: 3