且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将datetime数据类型转换为字符串MVC

更新时间:2023-01-30 18:30:19

你显示的代码将昨天日期的格式化字符串版本放入FromDateString中 - 它不能执行任何其他操作,并且每次执行该代码时都会执行此操作。



并且有一个问题:因为FromDateString为null意味着您根本没有执行该代码!为什么不?我们不知道 - 我们不知道你的其余代码是如何工作的。



所以从调试器开始,然后在那里放几个断点。第一个出现在上面显示的行上,当你使用FromDateString做任何事情时,其他的就行了:将它传递给方法,打印它,每个地方。

现在运行你的代码,并查看此处显示的代码是否在对变量进行任何其他访问之前执行。如果不是,那么你需要查看你的代码并找出原因 - 我们不能为你做到这一点!

如果是,那么你需要看一下定义FromDateString - 它是一个局部变量,它掩盖了同名的类级变量,然后意味着你永远不会设置类级别的版本?再次 - 我们无法分辨!


I am doing a project and I got confused in an area that how to convert the date time to string value?

controller

var FromDate = DateTime.Now.AddDays(-1);
                FromDateString = FromDate.ToString();



I am getting correct value to fromdate but it is not passing to FromDateString. This FromDateString have given in parameter of an action method and getting value.
My only problem is that how can I convert this datetime to string ??
FromDateString is given as string and this cannot be changed. Is it possible to do that ?
can anyone please help me to correct my code ??

What I have tried:

have searched for code but didn't get how to write in controller .

The code you show puts a formated string version of yesterday's date into FromDateString - it can't do anything else, and will do so every time you execute that code.

And there is the rub: for FromDateString to be null means that you haven't executed that code at all! Why not? We don't know - we have no idea how the rest of your code works.

So start with the debugger, and put a couple of breakpoints in there. The first one goes on the lines you show above, and the other(s) go when you use FromDateString for anything: passing it to a method, printing it, every where.
Now run your code, and see if the code you show here is executed before any other access to the variable. If it isn't, then you need to look at your code and find out why not - we can't do that for you!
If it is, then you need to look at the definition of FromDateString - is it a local variable that masks a class level variable of the same name and then means you never set the class level version? Again - we can't tell!