Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format JS Date as a C# compatible DateTime?

I've passed a Javascript DateTime picker date from a view to an MVC controller action.

The format of the string when passed to the controller action is Thu Jul 28 2016 17:05:00 GMT+0100 which causes an invalid operation exception converting String to DateTime. in C#.

This is how I assign the value of the Date picker to the hidden field value:

$('#OutageStart').val(e.date)

How can you format JS Date string as a C# compatible DateTime?

The binding error is thrown in the C# custom model binder that tries to bind the JS Date string value to a Nullable<DateTime>:

public class DateTimeBinder : System.Web.Mvc.IModelBinder
{


    public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

        return value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);
    }
}
like image 769
Brian Var Avatar asked Jan 19 '26 03:01

Brian Var


1 Answers

alternatively you can use timestamp for the conversion and user's timezone won't effect your result

in js

myDateObject.getTime() //-> outputs a timestamp (integer)

in c# (if you have .NET 4.6+)

DateTimeOffset.FromUnixTimeSeconds(timestamp);

otherwise

System.DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(timestamp).ToLocalTime();
like image 184
Steve Avatar answered Jan 20 '26 17:01

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!