将Json解析日期转换为适合html5输入日期

时间:2017-06-02 10:15:01

标签: javascript json asp.net-mvc html5 knockout.js

我正在使用Knockout制作一个漂亮的Gui,就像这样

使用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);
    });
});

EndDate是一个日期时间?从这样的控制器解析

return Json(list, JsonRequestBehavior.AllowGet);

这是我的输入,我想把Date放入,所以我可以编辑它。

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

如何将日期格式化为正确的格式?所以我可以在输入类型=日期?

中使用它

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));
    }
}

编辑以显示更新的操作:

`  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;



        }`

感谢。 尼。

3 个答案:

答案 0 :(得分: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());

答案 1 :(得分:0)

您可以将Json Serializer设置应用于所需的日期格式,同时从Controller的Action Action中返回JSON日期,如下所示:

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

您可以从Controller返回您的集合[需要将行动的返回类型更改为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;

你会得到Json的回应&#34;成功&#34;对象,您可以根据自己的要求进行更改。

然后你可以通过以下方式将它绑定到你的datepicker控件之前去实现它:

JsonConvert.DeserializeObject<DateTime>(yourDate);

答案 2 :(得分:0)

看看这篇文章:

How do I format a Microsoft JSON date?

说明了一种方法:

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

在您的实例中,要么在将值分配给视图模型时更改值,要么添加一个计算的observable,以便在检索它时将其转换。