繁体   English   中英

如何在ASP.NET MVC控制器参数中将毫秒转换为DateTime

[英]How to convert milliseconds to DateTime in ASP.NET MVC controller parameter

甘特图将时间(以毫秒为单位)传递给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值?

毫秒不能代表日期。 毫秒是用于测量持续时间的单位。 因此,询问如何将持续时间转换为DateTime C#对象没有任何意义。

另一方面,自时间中某个固定日期(例如The Epoch )可以表示DateTime以来经过的毫秒数。 我不熟悉您使用的客户端库及其代表的毫秒数,但出于本示例的目的,我们假设它们代表自1970年1月1日UTC时间以来经过的毫秒数。 在这种情况下,您可以简单地将其转换为相应的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的精确算法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM