甘特图以毫秒为单位将时间传递给MVC4控制器。下面的代码打印出1440190800000
$(".gantt").gantt({
onAddClick: function (dt, rowId) {
alert(dt);
window.location.href='NewBooking?' + $.param({
datetime: dt,
row: rowId
});
},
MVC4控制器有签名:
public ActionResult NewBooking(DateTime datetime, string row)
{
var m = new NewBookingViewModel();
return View(m);
}
调用此控制器会导致错误。
The parameters dictionary contains a null entry for parameter 'datetime' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult NewBooking(System.DateTime, System.String)' in 'Eeva.Erp.Controllers.BookingController'. An optional parameter must be a
since milliseconds are not contverted to datetime.
如何在控制器代码或javascript中修复这一点以获得DateTime值?
发布于 2015-08-02 03:31:03
毫秒不能表示日期。毫秒是测量时间持续时间的单位。因此,询问如何将时间持续时间转换为DateTime C#对象是没有意义的。
另一方面,由于时间中的某个固定日期(如The Epoch)可以表示一个DateTime,因此经过了毫秒。我不熟悉您正在使用的客户端库以及这些毫秒代表的是什么,但为了本例的目的,让我们假设它们表示自1970年1月1日以来所经过的毫秒数00:00:00协调时。在这种情况下,您可以简单地将其转换为相应的DateTime对象:
public DateTime FromUnixTime(long unixTime)
{
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
return epoch.AddMilliseconds(unixTime);
}
然后:
public ActionResult NewBooking(long datetime, string row)
{
DateTime someDate = FromUnixTime(datetime);
var m = new NewBookingViewModel();
return View(m);
}
显然,可以进一步改进这些代码,以便在自定义模型绑定器中进行这种转换,然后控制器操作可以直接接受DateTime对象参数。
现在,这取决于您和您正在使用的js库的文档,它们详细说明了将这些毫秒转换为DateTime的精确算法。
https://stackoverflow.com/questions/31771259
复制相似问题