Question

I have Date time input field from where I am taking date and converting it to another format, my code for that

try
{
    DateTime dt = dtiFrom.Value.Date;
    string format = "DD-MM-YYYY"; // Use this format
    MessageBox.Show(dt.ToString(format)); // here its shows result as DD-10-YYYY
    DateTime dt1 = Convert.ToDateTime(dt.ToString(format)); // here Error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0."
}
catch (Exception ee)
{
    MessageBox.Show(ee.Message, "Error Message!");
}

I am not able to convert date according to my format. please could any body help me in code or suggest me some code. thanks in advance

Was it helpful?

Solution

Your format should be as follows:

string format = "dd-MM-yyyy";

Casing is important with string formatting, you may think it strange that the month uses upper-case, but this is because lower case m and mm is used to represent minutes.

Note that the reason your output displays DD and YYYY is because any character that is not reserved as a format character will be outputted with no change. Uppercase D and Y are not reserved which is why they display in the output, just as - remains unchanged.

If you wish to output reserved format characters then you can escape them using \.

See here for a full list of date and time format values

OTHER TIPS

Date pattern format should be changed and better to use TryParseExact instead of using Convert

DateTime dt = dtiFrom.Value.Date;
string format = "dd-MM-yyyy";
DateTime dt1 = new DateTime();

if (DateTime.TryParseExact(dt , format, null , DateTimeStyles.None, out dt1))
{
  // you can use dt1 here
}
else
{
  MessageBox.Show("Error Massage");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top