1

i try to get a time from Ajax request dateType json . the result i get is :

 /DATE(1436688000000)/ 

heres my code :

view:

  <div class="col-sm-8">

      @Html.DropDownListFor(model => model[i].MovieShowTime.Single().MovieID, SelectMovieID, "Select Movie", new { id = "MovieName", name = "MovieName" })
      @Html.DropDownListFor(x => x[i].MovieShowTimeID, Enumerable.Empty<SelectListItem>(), "--Loading Value--", new { id = "ShowTime", name = "ShowTime" })
      @Html.ValidationMessageFor(model=>model[i].MovieShowTimeID)
  </div>

controller :

        public JsonResult GetShowTime(int? MovieID)
    {

        var data = (from m in db.MovieShowTimes
                    where m.MovieID == MovieID
                    select new
                    {
                        id = m.MovieShowTimeID,
                        name = m.ShowTime
                    }).ToList();

        return Json(data, JsonRequestBehavior.AllowGet);
    }

ajax : .

           $(function () {
            $('#MovieName').change(function () {
            $.ajax({
            type: "POST",
            url: '@Url.Action("GetShowTime", "TimeScreening")',
            data: { MovieID: $('#MovieName').val() },
            dataType : 'json',
            success: function (data) {
                $('#ShowTime').html('');

                //alert(ChangeDateFormat("\/Date(1319266795390+0800)\/"));
                $.each(data, function (id, option) {
                    var name = ChangeDateFormat(option.name)
                    $('#ShowTime').append($('<option></option>').val(option.id).html(option.name));
                });

            },
            error: function (xhr, ajaxOptions, thrownEror) {
                alert("False" + xhr +"..."+ ajaxOptions +"... "+ thrownEror);
            }
        });
    });
});

i see the threds about convert form json to C# datetime but none of them have resolved the problem . follow by this post: JSON-Serialization-and-Deserialization-in-ASP-NET this jave me the closet answer , but this in date.

code:

function ChangeDateFormat(jsondate) {
 jsondate = jsondate.replace("/Date(", "").replace(")/", "");
 if (jsondate.indexOf("+") > 0) {
     jsondate = jsondate.substring(0, jsondate.indexOf("+"));
 }
 else if (jsondate.indexOf("-") > 0) {
     jsondate = jsondate.substring(0, jsondate.indexOf("-"));
 }

 var date = new Date(parseInt(jsondate, 10));
 var month = date.getMonth() + 1 < 10 ? 
    "0" + (date.getMonth() + 1) : date.getMonth() + 1;
 var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
 return date.getFullYear() + "-" + month + "-" + currentDate;
 }

this answer : Format a Microsoft JSON date really no ugly parsing but this gave me a datetime.now and no close to time.

this answer : ASP.NET MVC JsonResult Date Format is the same.

and this artical is good but the same.. dates-and-json

so.. what i need to do?

Community
  • 1
  • 1
Ziv Daniel
  • 95
  • 8

1 Answers1

1

I have this set of functions

// START Datetime Converters
function DateConverter(date) {
    var aux = null;
    if (date != null) {
        aux = date.substring(6);
        aux = aux.substring(0, aux.indexOf(')'));
    }

    return aux != null ? getISODate(new Date(parseInt(aux))) : "";
}

function DatetimeConverter(date) {
    var aux = null;
    if (date != null) {
        aux = date.substring(6);
        aux = aux.substring(0, aux.indexOf(')'));
    }

    return aux != null ? getISODateTime(new Date(parseInt(aux))) : "";
}

function getISODate(d) {
    // padding function
    var s = function (a, b) { return (1e15 + a + "").slice(-b) };

    // default date parameter
    if (typeof d === 'undefined') {
        d = new Date();
    };

    // return ISO datetime
    return zeroPad(d.getDate(), 2) + '/' +
    zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
    zeroPad(d.getFullYear(), 4);
}

function getISODateTime(d) {
    // padding function
    var s = function (a, b) { return (1e15 + a + "").slice(-b) };

    // default date parameter
    if (typeof d === 'undefined') {
        d = new Date();
    };

    // return ISO datetime
    return zeroPad(d.getDate(), 2) + '/' +
    zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
    zeroPad(d.getFullYear(), 4) + " " +
    zeroPad(d.getHours(), 2) + ":" +
    zeroPad(d.getMinutes(), 2) + ":" +
    zeroPad(d.getSeconds(), 2);
}

function zeroPad(num, places) {
    var zero = places - num.toString().length + 1;
    return Array(+(zero > 0 && zero)).join("0") + num;
}
// END Datetime Converters

Example: In a table where i show the CreatedDate:

{
    "mRender": function (oAux, oType, oData) {
        return DateConverter(oData.CreatedDate);
    },
},

If you want Date and Time just use DatetimeConverter

What i'm doing

Inside the function DateConverter and DateTimeConverter i catch the number without the \DATE... like "1436688000000".

Then inside the getISODate, in the first line:

var s = function (a, b) { return (1e15 + a + "").slice(-b) };

Is a padding function. Where the day 2 will become "02" if you use it like:

s(d.getDate(), 2)

If the date that the action returns is null or invalid:

if (typeof d === 'undefined') {
     d = new Date();
};

The other padding function is zeroPad that does what the function s() does but doesn't remove the left numbers, example:

var a = 3000;
var sA = s(3000, 2);
var zpA = zeroPad(3000, 2);

sA will become "00" while zpA will keep "3000"

PS: I can't remember why i used s function... i think that i forgot to delete it after creating zeroPad.

Leandro Soares
  • 2,902
  • 2
  • 27
  • 39