Custom JavaScriptConverter for DateTime?

前端 未结 10 791
走了就别回头了
走了就别回头了 2020-12-02 19:18

I have an object, it has a DateTime property... I want to pass that object from an .ashx handler back to a webpage via AJAX/JSON... I don\'t want to use 3rd party controls..

10条回答
  •  猫巷女王i
    2020-12-02 19:29

    I know this looks really dumb, but so far I haven't found anything better...I'm still looking though, so comments are welcome.

    new JavaScriptSerializer().Serialize(DateTime.Now).Replace("\"\\/", "").Replace("\\/\"", "");
    

    This just removes the quotes and slashes, so the output is just Date(123456789) which, though technically not a literal, is understood by the browser as an actual date value and not a string.

    In JSON, it would look like this

    {"myDate":Date(123456789)}
    

    A hack, I suppose. If this is actually implemented in production code, I'd personally wrap it up, either in an extension method like FormatForDates() or wrap the serializer itself as in a decorator pattern...or in this case, an "undecorator." I must really be missing the boat as to why this seems so hard. I just want to render a date, people! :-p

提交回复
热议问题