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 HorvatPosted Jul 6, 2011, 7:35 AM
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
Guest UserPosted Jul 6, 2011, 7:32 AM
public string ConvertDate(string oldDate)
{
return String.Format("{0:dd/MM/yyyy}", DateTime.Parse(oldDate));
}
Posted Jul 6, 2011, 7:30 AM
Posted Jul 6, 2011, 7:29 AM