Parsing into a string from type DateTime

80 views Asked by At

I am trying to convert a DateTime and an int property into a string in a foreach loop. I need to put the information that is stored in the objects properties into the variables and then use that info to write to a text file using StreamWriter. I'm not quite sure what I am doing wrong. Parse is red underlined with this error message -

Error 2 'string' does not contain a definition for 'Parse'

Here is my code -

 public bool Save()
        {
            string appointStart;
            string appointLength;
            string appointDescription;

            foreach (Appointment appointment in appointments)
            {
                appointStart = string.Parse(appointment.Start);
                appointLength = string.Parse(appointment.Length);
                appointDescription = appointment.DisplayableDescription;

            }
            return true;
        }

Thank you

2

There are 2 answers

1
Jehof On BEST ANSWER

Use the ToString() methods of DateTime and Int32 class to get a string representation of the specified types. Some ToString() methods provide overloads to define the formatting of the string value.

foreach (Appointment appointment in appointments)
{
  appointStart = appointment.Start.ToString();
  appointLength = appointment.Length.ToString();
  appointDescription = appointment.DisplayableDescription;
}
2
Surbhi Harsh On

Why do you need to Parse the DateTime and int into String?? Because if you just want to have the variables in string format, you can simply use .ToString() or Convert.Tostring()