15

This code gives me this error:

var n = "9/7/2014 8:22:35 AM";
var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

But this code works as it should and returns the date in the proper format.

var n = DateTime.Now;
var m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

Anyone know why the first code isn't working and how to get it working?

3
  • They're entirely different types. A DateTime is not a string. Look at their respective documentation. Sep 7, 2014 at 15:33
  • Strings aren't dates.
    – SLaks
    Sep 7, 2014 at 15:36
  • You really shouldn't use var in these cases. Why? Read @JeroenVannevel's comment.
    – Cole Tobin
    Sep 7, 2014 at 16:49

2 Answers 2

34

You need to understand how static typing works. In the first one, the type of n is string. The type string does have a ToString() method, but that method either takes no arguments and returns the same string object, or it takes a format provider. Since you provided an argument, the compiler assumes you meant the second version, but the types don't match.

Perhaps what you are trying to do is convert a string into a date first, which can be done by parsing it using DateTime's Parse or TryParse methods:

var n = DateTime.Parse("9/7/2014 8:22:35 AM");

Here, we convert a string to DateTime. The type of n is DateTime.

I think it might be a good idea not to use var while you're figuring out C#. If you explicitly list the types, you'll gain a greater understanding of what's going on, and the compiler will flag errors earlier. In this case, you'll get the error on the very first line, and it'll be obvious. It will complain about assigning a string to a DateTime. No weird stuff about IFormatProvider, which is not at all obvious. Your code would look like this:

DateTime n = "9/7/2014 8:22:35 AM";
string m = n.ToString("yyyy-MM-dd'T'HH:mm:ssZ");

In this example, you'll get an error on line one, and then you can clearly see that you are trying to assign a literal value (the string "9/7/2014 8:22:35 AM") of type string to a variable of type DateTime, which can't work.

0
3
var n = "9/7/2014 8:22:35 AM";

This is treated as String. You may try this to work

var n = DateTime.Parse("9/7/2014 8:22:35 AM");

var n = DateTime.Now;

This is a DateTime object

1
  • Ok so how do I make this convert code work? I'm fairly new to c#. Sep 7, 2014 at 15:35

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.