Parsing error while converting javascript datetime into C#

244 views Asked by At

I am using kendo time picker to show time on the UI. The widget submits the time in the following format Mon May 16 2016 01:00:00 GMT-0500 (Central Daylight Time)

I followed the article here to convert the datetime into .Net datetime object However i am getting error while parsing

{"String was not recognized as a valid DateTime."}

Once the date is parsed i want to convert it into UTC and store the time portion into database.

    [HttpPost]
    public ActionResult Save(MyModel model)
    {                  
        // getting error at line below while parsing    
        DateTime dt = DateTime.ParseExact(model.SelectedTimeString.Substring(0,33),
                       "ddd MMM d yyyy HH:mm:ss GMT-zzzz",
                        CultureInfo.InvariantCulture);           

         var utcTime = dt.ToUniversalTime().TimeOfDay;

        // store utcTime in database here

        return View("Index", model);
    }

cshtml

    @using (@Html.BeginForm("Save", "Home"))
    {
        <div class="row">
            <div class="col-lg-6">
                @(Html.Kendo().TimePickerFor(x => x.SelectTime).Events(e => e.Change("changeDate")))           
                @Html.HiddenFor(x=>x.SelectedTimeString)          
            </div>
        </div>
        <button type="submit">Save</button>
    }

javascript

    <script type="text/javascript">
        function changeDate() {      
            var kendoDate = $('#SelectTime').getKendoTimePicker();       
            $('#SelectedTimeString').val(kendoDate.value());
        }
    </script>
1

There are 1 answers

0
David Yates On

The following will return a date object or null if the date picker is blank or the value is invalid:

var data = $('#SelectTime').data('kendoDatePicker').value();

You can test it by assigning it to a variable and doing data.getFullYear(). Afterwards, you could use:

var dataAsJsonString = JSON.stringify(data);

This will return a UTC date that as a string that looks like this: "2011-10-10T05:00.000Z"

Here is an example fiddle: http://jsfiddle.net/MadCodeMonkey/191a7c53/