Hrvoje said:
How to convert text from textbox "12.05.1977" into "12/05/1977"? and also
check if the text is in right format before converting?
What type do you want the data to be in when you're done? Your post
literally taken is asking to reformat a string into a different string.
Is that what you want? Or do you really want a DateTime object when
you're done?
If you want a string, one possibility is to use the String.Replace()
method, as suggested in Ashot's post (but of course you wouldn't bother
with the DateTime.Parse() call in his code). Of course, that wouldn't
check the format for you.
If you want a DateTime, then IMHO it is pointless to do any string
conversion first (including the call to String.Replace() that Ashot
suggests). Assuming the input string must be in the format you've
provided, this code will check the format and convert at the same time:
DateTime dt;
string strInput = "12.05.1977";
if (DateTime.TryParseExact(strInput, "MM.dd.yyyy",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
// String is a correctly formatted DateTime, and
// the value is now in the dt variable.
}
If you want a string, AND you do want to verify that the original string
is parse-able as a DateTime, then I would actually use the above, and
then inside the if() statement's block, include this:
string strOutput = dt.ToString("MM/dd/yyyy");
You could of course do some explicit checking of the format yourself,
and doing so could even have better performance (especially since the
format conversion at that point is a simple search-and-replace, rather
than a full DateTime-to-string conversion), but it seems to me that the
DateTime class formatter will do just that, with easy-to-read, simple code.
Pete