C # Convert or parse a variable into DateTime

I need to write a short piece of code to take a variable and then convert it to a DateTime type. Unfortunately, he continues to talk about this in the assembly, but when I run it, he gives me an error, because he does not see it as a variable, but as a string.

DateTime dateValue = (Convert.ToDateTime("@DeliveryDate")); 
+4
source share
3 answers

You misunderstood how variables work. In C #, variables must reference their identifier in code. C # does not support replacing strings with variables like you might find in a language such as PHP .

Assuming you defined a variable in the code and populated it with a value from the database:

 string deliveryDate = (string)command.ExecuteScalar(); 

You can convert it to DateTime as follows:

 DateTime dateValue = Convert.ToDateTime(deliveryDate); 
+4
source

Why not use:

 string DeliveryDate = @"01/01/2011"; // I assume DeliveryDate is some variable you defined before DateTime dateValue = DateTime.Parse(DeliveryDate) 
0
source

Try this instead:

 String deliveryDate = "2013-07-31 23:12:00"; DateTime dateValue = Convert.ToDateTime(deliveryDate); 
0
source

Source: https://habr.com/ru/post/1494573/


All Articles