0

I am using Knockout to make a nice looking Gui like so

Javascript:

viewModel = {
    lookupCollection: ko.observableArray()
};

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url:  "@Url.Action("GetView", "FakturaOmfangs", new {area = "" , id = ViewBag.id})",
    }).done(function (data) {
        $(data).each(function (index, element) {
            var mappedItem =
                {
                    FakturaId: ko.observable(element.FakturaId),
                    FakturaProdukterId: ko.observable(element.FakturaProdukterId),
                    Beskrivelse: ko.observable(element.Beskrivelse),
                    Periode: ko.observable(element.Periode),
                    EndDate: ko.observable(element.EndDate),
                    procent: ko.observable(element.procent),
                    Rabat: ko.observable(element.Rabat),
                    Pris: ko.observable(element.Pris),
                    Ialt: ko.observable(element.Ialt),
                    Value: ko.observable(element.Value),
                    Mode: ko.observable("display")
                };
            console.log(mappedItem);
            viewModel.lookupCollection.push(mappedItem);
        });
        ko.applyBindings(viewModel);
    });
});

the EndDate is a Datetime? parsed from controller like this

return Json(list, JsonRequestBehavior.AllowGet);

This is my input where i would like to put the Date into, so i can edit it.

<td><input class="form-control" type="date" data-bind="value: EndDate" /></td>

How do i format the date to the correct format? so that i can use it in input type=Date ?

Output from Log EndDate: "/Date(1494885600000)/"

Modelclass:

 public class FakturaOmfang
{
    //if selected type dropdown
    [Key]
    public int Id { get; set; }

    public string Beskrivelse { get; set; }
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime? Periode { get; set; }
    [JsonProperty]
    [JsonConverter(typeof(ShortDateConverter))]
    public DateTime? EndDate { get; set; }

    public int? Dage { get; set; }
    [DisplayName("Ydet %")]
    [Range(0,100)]
    public int? procent { get; set; }
    [Range(0, 100)]
    public int? Rabat { get; set; }
    [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
    public decimal Pris { get; set; }
    [DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
    public decimal Ialt { get; set; }

    public int FakturaId { get; set; }
    public Faktura Faktura { get; set; }

    public int FakturaProdukterId { get; set; }
    public FakturaProdukter FakturaProdukter { get; set; }



}
public class ShortDateConverter : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return DateTime.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((DateTime)value).ToString(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern));
    }
}

Edit to show updated Action:

`  public ContentResult GetView(int? id)
        {

            var list = db.FakturaOmfangs.Where(x => x.FakturaId == id).ToList();

            ViewBag.FakturaProdukterId = new SelectList(db.FakturaProdukters, "Id", "Overskrift");

            var result = new ContentResult(
                  Content = JsonConvert.SerializeObject(new { success = list }), Formatting.None, new JsonSerializerSettings()
                  {
                      ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                      NullValueHandling = NullValueHandling.Include,
                      DateFormatString = "dd/MM/yyyy"
                  },
                   ContentType = "application/json");
            return result;



        }`

Thanks. Benny.

Benny
  • 3
  • 4

3 Answers3

0
    Updating Model Class:-

    [JsonProperty]
    [JsonConverter(typeof(ShortDateConverter))]
    public DateTime EndDate { get; set; }

    //// Adding New File:-
    public class ShortDateConverter : DateTimeConverterBase
    {
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
           return DateTime.Parse(reader.Value.ToString());
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {         
            writer.WriteValue( ((DateTime)value).ToString(CurrentCulture.DateTimeFormat.ShortDatePattern));
        }
    }

======================================================================

    EndDate: ko.observable(new Date(parseInt(element.EndDate.substr(6))))

//// Or 

    Updating Model Class:-
    [JsonProperty]
    [JsonConverter(typeof(IsoDateTimeConverter))]
    public DateTime EndDate { get; set; }

//// Or

     WebApiConfig.cs File:-
     config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
             new IsoDateTimeConverter());
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
  • Hey, thanks for the quick answer. I have tried first and 2nd method couldn't get any of them to work. when parsed to view EndDate looks like this : "/Date(1494885600000)/". – Benny Jun 02 '17 at 10:43
  • @Benny: I had updated the answer. Please try ShortDateConverter solution – Thulasiram Jun 02 '17 at 11:03
  • Because type="date" expect mm/dd/yyyy current culture date only.... https://jsfiddle.net/wrkhxs84/ – Thulasiram Jun 02 '17 at 11:04
  • i have tried it with the ShortDateConverter, but my output to the view is still EndDate: "/Date(1494885600000)/". – Benny Jun 02 '17 at 11:17
  • Can u please take screen short of the code (Model Class) and share link? – Thulasiram Jun 02 '17 at 11:21
  • i have edit question, and added the modelclass + the ShortDateConverter – Benny Jun 02 '17 at 11:26
0

You can apply Json Serializer setting to your required date format while returning JSON date from your Controller's Action Method something like this :

 new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                    NullValueHandling = NullValueHandling.Include,
                    DateFormatString = "dd/MM/yyyy"
                })

You can return your collection from Controller something like this [You need to change return type of action to ContentResult :

 var result = new ContentResult
        {
            Content = JsonConvert.SerializeObject(new { success = Collection },
            Formatting.None,
            new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                NullValueHandling = NullValueHandling.Include,
                DateFormatString = "dd/MM/yyyy"

            }),

            ContentType = "application/json"
        };
        return result;

You will get Json response in "success" object , you can change it as per your requirement.

And then you can deserealize it before binding it to your datepicker control by something like this :

JsonConvert.DeserializeObject<DateTime>(yourDate);
Benny
  • 3
  • 4
Nikunj Patel
  • 249
  • 3
  • 13
0

Check out this post:

How do I format a Microsoft JSON date?

which illustrates a way to do it:

var date = new Date(parseInt(jsonDate.substr(6)));

In your instance, either change the value when you go to assign the value to the view model, or add a computed observable that will convert it when retrieving it out.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257