简体   繁体   中英

How to convert JSON.NET datetime format to javascript date and time

I can't believe I ask this kind of question. But I had to do it as I don't have much hairs left to stretch.

I am using MVC4 RC WEB API and knockout. If I call GET method of the web api, I get an object with a datetime property which was automatically converted as a string such as '2012-05-12T00:00:00' via JSON.NET.

But how can I convert this string to javascript format to use jquery ui such as calendar? I tried various methods in vain.

UPDATE: I believe it was not Date class. It was jquery calendar (and me, of course). I didn't know I had to specify minDate like this to show correct value of the date. Maybe there is better way to do it?

        <div class="editor-label">Date:             </div>
        <div class="editor-field">
                <input data-bind="datepicker: selectedGroup().InspectionDate, 
                      datepickerOptions: { minDate: selectedGroup().InspectionDate }">
                </input>
        </div>    

Javascript Console (Chrome):

>>Date("2012-05-12T00:00:00")
Fri May 11 2012 19:00:00 GMT-0500 (Central Daylight Time)

Date() isn't working for you?

2 ways really.

  1. Brute-force: Split up the string, getting the year, month, day etc and call the relevant methods on javascript date such as setYear , setMonth , setDate etc

  2. Use a library such as date.js which tend to have better support for parsing strings to dates than the native Date object

This also seems to cover what you want exactly: https://github.com/csnover/js-iso8601/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM