In above textfield date comes likes this "05/Jul/2011". I need to convert the datetime into "05/07/2011".
Datetime format
hi all,
In above textfield date comes likes this "05/Jul/2011". I need to convert the datetime into "05/07/2011".
In above textfield date comes likes this "05/Jul/2011". I need to convert the datetime into "05/07/2011".

Zoran HorvatRank #792 · 2.9K reputationPosted Jul 6, 2011, 3:35 AM EDT
try
{
string raw = "05/Jul/2011";
DateTime dt = DateTime.Parse(raw);
string formatted = dt.ToString("dd/MM/yyyy");
Console.WriteLine(formatted);
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
Make sure that all exceptions are handled because user is free to enter garbage in the text box. You can enforce input string to be in the format stated in your question by matching it against a regular expression:
try
{
string raw = "05/Jul/2011";
Regex reg = new Regex(@"\d[\d]/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/\d\d[\d\d]");
if (reg.IsMatch(raw))
{
DateTime dt = DateTime.Parse(raw);
string formatted = dt.ToString("dd/MM/yyyy");
Console.WriteLine(formatted);
}
else
{
Console.WriteLine("Incorrect input string.");
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
In this code, if you change string raw = "05/07/2011", that would print out "Incorrect input string." without exception.
Zoran
Posted Jul 6, 2011, 3:29 AM EDT
Posted Jul 6, 2011, 3:30 AM EDT
Guest UserRank #1,422 · 1.2K reputationPosted Jul 6, 2011, 3:32 AM EDT
public string ConvertDate(string oldDate)
{
return String.Format("{0:dd/MM/yyyy}", DateTime.Parse(oldDate));
}