Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot convert from 'string' to 'System.IFormatProvider'

Tags:

c#

asp.net

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?

like image 503
Control Freak Avatar asked Sep 07 '14 15:09

Control Freak


2 Answers

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.

like image 196
siride Avatar answered Nov 14 '22 09:11

siride


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

like image 25
Rahul Tripathi Avatar answered Nov 14 '22 08:11

Rahul Tripathi