4

I'm trying to convert a DateTime to a string but actually the dt variable passed in the getFixtures method is underlined in red.

DateTime dt = DateTime.ParseExact(Calendar.SelectedDate.Value.ToString(), "ddMMyyyy",
                                  CultureInfo.InvariantCulture);
dt.ToString("ddMMyyyy");

fixtures.getFixtures(dt);

Error:

Can't convert DateTime to string.

What am I doing wrong?

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
Harold Finch
  • 576
  • 11
  • 32
  • 4
    I _strongly_ suspect `Calendar.SelectedDate.Value` is _already_ a `DateTime` I never heard such an error or exception message before. On which line you get this? What is the complete message? What `fixtures.getFixtures(dt)` do? And you need to assign to something what `ToString` method returns. – Soner Gönül Jul 31 '15 at 11:26
  • possible duplicate of [Parse string to DateTime in C#](http://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) – Joy Rex Jul 31 '15 at 11:28

4 Answers4

7

Seems you want pass a string to the getFixtures but actually you are passing the dt which is a DateTime.

dt.ToString("ddMMyyyy"); does not change the dt to string, so you should save it's output to a string and use that string. Here is the code:

var stringDt = dt.ToString("ddMMyyyy");

fixtures.getFixtures(stringDt );
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
5

Your code:

dt.ToString("ddMMyyyy");
fixtures.getFixtures(dt);

If you want to pass string representation of datetime inside a method, change it to :

fixtures.getFixtures(dt.ToString("ddMMyyyy"));
Fabjan
  • 13,506
  • 4
  • 25
  • 52
0

instead of,dt.ToString("ddMMyyyy"); fixtures.getFixtures(dt);

use

string dttime=dt.ToString("ddMMyyyy");
fixtures.getFixtures(dttime); 

using dt.ToString("ddMMyyyy") does not converts dt to string, it just returns a new string, dt remains datetime as it was.

Kryptonian
  • 860
  • 3
  • 10
  • 26
0

This is an old way but it works. I added to the model.

private string _displayDate;

    [Display(Name="Display Date")]
    [DataType(DataType.Text)]
    public string DisplayDate
    {
        get
        {
            DateTime dt = new DateTime();
            dt = Convert.ToDateTime(_displayDate);
            return dt.ToShortDateString();
        }
        set { _displayDate = value; }

    }

//Displays: 3/2/1996