I need a method that converts a string to a datetime. The format for the datetime must be dd/MM/yyyy
If the string is in any other format, the method will return null.
This is wat I have so far :
private DateTime? StringToDateTime(string value)
{
DateTime? Result = null;
DateTime test = DateTime.Now.Date;
if (DateTime.TryParseExact(value, "dd/MM/yyyy", System.Globalization.CultureInfo.InstalledUICulture, System.Globalization.DateTimeStyles.None, out test))
Result = test;
return Result;
}
and to test it I use this
private void button1_Click(object sender, EventArgs e)
{
string value = "01/01/2015";
DateTime? test = StringToDateTime(value);
if (test == null)
MessageBox.Show("invalid date entered");
else
MessageBox.Show(test.ToString());
}
Now the problem is that the TryParseExact
always fails. I also tried "dd/mm/yyyy"
as format, but with same results.
So I must be doing something wrong here. Does anybody has an example how to use DateTime.TryParseExact
or is there another way of doing this ?
EDIT: This is not a duplicate since the "duplicate" link advises to use TryParseExact while my question is using this from the start and is asking why it does not work
Change your code to:
DateTime? Result = null;
DateTime test = DateTime.Now.Date;
if (DateTime.TryParseExact(value, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out test))
Result = test;
The change is to use CultureInfo.InvariantCulture instead of CultureInfo.InstalledUICulture .
For me the format was an issue, with the following code it accepts 01/01/2015 as well as 1/1/2015 ( dd/MM/yyyy
and d/M/yyyy
):
DateTime? Result = null;
DateTime test = DateTime.Now.Date;
var formats = new[] { "dd/MM/yyyy", "d/M/yyyy" };
if (DateTime.TryParseExact(value, formats , System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out test))
Result = test;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.