Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Formatting the date from JSON and working with it on client side

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 197
    Comment on it

    "Asp.net formatting a date from JSON and working with it on clinet side"

        While dealing with JSON I got an issue that dates in the JSON are serialized as plain strings.

        The solution which I got for this problem is :   As data types supported in JSON include string, number, boolean, array, object and null,there is no data type for dates in JSON therefore the dates are serialized as plain strings.

     The date in JSON is serialised in the following form:

    \/Date(ticks)\/ - where ticks is the number of milliseconds since 1 January 1970.

    For example:
    The date recieved in JSON gets serialised in following format:
    OrderDate:"/Date(123456789123)/"

      So inorder to get the date in the correct format use the following code:-

    function ToJavaScriptDate(inputdate) 
    {
      var pattern = /Date\(([^)]+)\)/;
      var results = pattern.exec(inputdate);
      var dt = new Date(parseFloat(results[1]));
      return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    }
    

    Explanation:

    ToJavaScriptDate() function recieves the inputdate parameter value in \/Date(ticks)\/ format. var pattern represents the regular expression . The exec() method takes the value of the inputdate, matches it with the pattern and then returns the array.

    For example:

    If the inputdate value is = \/Date(123456789123)\/ then results[1] will be 123456789123.
      Now the Date object converts the result obtained by the exec() method into a valid date which is stored in dt, thus we can retrieve the valid date from dt.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: