Asp.net 将天数/时间转换为时间跨度
没有找到我要找的东西。我有用asp编写的代码,我正在尝试将它们转换为timespan asp.net mvc:Asp.net 将天数/时间转换为时间跨度,asp.net,Asp.net,没有找到我要找的东西。我有用asp编写的代码,我正在尝试将它们转换为timespan asp.net mvc: <% days = DateDiff("d",year(rs("create_dt")) & "-" & month(rs("create_dt")) & "-"
<%
days = DateDiff("d",year(rs("create_dt")) & "-"
& month(rs("create_dt")) & "-"
& day(rs("create_dt")),date())
if days=0 then days=1
db_totalrecords=clng(rs("cnt"))
periodcount=periodcount+db_totalrecords
response.write db_totalrecords
%>
行动方法:
public ActionResult ForcesDBValuesStat()
{
List<StatDBValues> myData;
using (GenesEntities context = new GenesEntities())
{
myData = m_statsWallRepository.GetDBValues(context);
}
ViewBag["myBag"] = DateTime.Now.ToString();
return View(myData);
}
public ActionResult ForcesDBValuesStat()
{
列出我的数据;
使用(GenesEntities context=newgenesentities())
{
myData=m_statsWallRepository.GetDBValues(上下文);
}
ViewBag[“myBag”]=DateTime.Now.ToString();
返回视图(myData);
}
一如既往地感谢。假设您在viewbag中获得了
create_dt
和cnt
作为DateTime
和Int32
变量,我会用c#/Razor语法说以下几句话
更新
视图包在mvc中是动态的。这意味着您可以将任何想要与视图通信的内容放入其中。这里我只是举个例子。关于你的原始问题,你应该关心的是,如果你减去c中的任何两个DateTime
变量,你会得到一个TimeSpan
。从那里,您可以调用TotalDays
,以获取以天表示的时间跨度
public ActionResult ForcesDBValuesStat()
{
List<StatDBValues> myData;
using (GenesEntities context = new GenesEntities())
{
myData = m_statsWallRepository.GetDBValues(context);
}
// set a "count" to be
// a random integer.
// should be comming from someware
// for example the database
ViewBag.cnt = 123;
// set the created date to a past date
ViewBag.create_dt = new DateTime(2015, 9, 13);
return View(myData);
}
public ActionResult ForcesDBValuesStat()
{
列出我的数据;
使用(GenesEntities context=newgenesentities())
{
myData=m_statsWallRepository.GetDBValues(上下文);
}
//将“计数”设置为
//一个随机整数。
//应该是从某处来的
//例如数据库
ViewBag.cnt=123;
//将创建日期设置为过去的日期
ViewBag.create_dt=新日期时间(2015,9,13);
返回视图(myData);
}
@{
var date=(DateTime)ViewBag.create\u dt;
var today=DateTime.today;
var天数=(今天-日期).TotalDays;
var db_totalrecords=(int)ViewBag.cnt;
如果(天数==0)
{
天数=1天;
}
}
测验
@日子
我收到的错误:无法将null转换为“System.DateTime”,因为它是不可为null的值类型描述:在执行当前web请求期间发生未处理的异常。请查看堆栈跟踪以了解有关错误的更多信息以及错误在代码中的起源。异常详细信息:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:无法将null转换为“System.DateTime”,因为它是不可为null的值类型OK我怀疑您没有控制器和/或您没有初始化ViewBag变量。你需要一些关于mvc的培训,才能让这些成为理由。是的,我正在学习。在我的控制器中,我使用的是使用上下文的列表。我是否能够按如下方式创建viewbag,或者我需要采用其他方法:viewbag[“myBag”]=DateTime.Now.ToString();请用您的操作方法中的代码以及实际的数据
类声明更新您的问题,如果可能,我将尝试更新我的答案只是更新了我的代码。不过,我不确定是否需要查看包
@{
var date = (DateTime)ViewBag.create_dt;
var today = DateTime.Today;
var days = (today - date).TotalDays;
var db_totalrecords = (int)ViewBag.cnt;
if (days == 0)
{
days = 1;
}
}
<h2>Test</h2>
@days