简体   繁体   中英

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

Gant chart passes time in milliseconds to MVC4 controller. Code below prints out 1440190800000

$(".gantt").gantt({
    onAddClick: function (dt, rowId) {
        alert(dt);
        window.location.href='NewBooking?' + $.param({
            datetime: dt,
            row: rowId
        });
    },

MVC4 controller has signature:

public ActionResult NewBooking(DateTime datetime, string row)
{
    var m = new NewBookingViewModel();
    return View(m);
}

Calling this controller causes error

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.

How to fix this in controller code or in javascript to get DateTime value ?

Milliseconds cannot represent dates. A millisecond is a unit for measuring time duration. So asking how to convert time duration into a DateTime C# object doesn't make sense.

On the other hand milliseconds elapsed since some fixed date in the time (like The Epoch ) can represent a DateTime. I am not familiar with the client library you are using and what those milliseconds represent but let's assume for the purpose of this example that they represent the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC time. In this case you could simply convert it to the corresponding DateTime object:

public DateTime FromUnixTime(long unixTime)
{
    var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    return epoch.AddMilliseconds(unixTime);
}

and then:

public ActionResult NewBooking(long datetime, string row)
{
    DateTime someDate = FromUnixTime(datetime);
    var m = new NewBookingViewModel();
    return View(m);
}

Obviously this code can be further improved so that this conversion is made in a custom model binder and your controller action could then directly take a DateTime object parameter.

So now it's really up to you and the documentation of the js library you are using to elaborate the precise algorithm for converting those milliseconds to a DateTime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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