Search code examples
javajqueryjspgsondate-formatting

How to convert to required date format inside jquery ajax script


In this case I have to assign date, which is inside the returned arraylist, to a textbox. The arraylist is returned inside script, ie a jquery ajax call to servlet and also it is in json format. data[0].demo_planned_on is the date returned and format is not as required. How do I use this particular object and covert it to required format (yyyy-dd-mm) and assign it to textbox, inside ajax script itself.How to convert to required format inside script itself where i receive the passed data .

servlet side:

 CustDAO cusName=new CustDAO();
        ArrayList<Cust> list2=cusName.dispCustomer2(abcd);
        new Gson().toJson(list2, response.getWriter());

jsp page:

 -------------
    -------------
    <tr><td>
    demo planned on :</td>
    <td><input type="text" id="dpo" name="dpo"  ></td></tr>
    </table>
        <script>
            $(document).ready(function(){
                var selected;


                $('#selectUsers').change(function(){
                    selected = $('#selectUsers').val();

                      $.ajax({
                        url: "Servlet2",
                        type: "Post",
                        data: {"selectUsers":selected},
                        dataType: "json",
                        success : function(data)
                            {



   $('#dpo').val(data[0].demo_planned_on); //getting wrong format here, during assignment of value to textbox with id="dpo". Need (yyyy-mm-dd) format. How to convert here itself??



                            }
                        });
                });
        </script>

Solution

  • var d=new Date("OCT 19,2016");
    var day = d.getDate();
    var month= d.getMonth()+1;
    var year = d.getFullYear();
    
    document.getElementById("demo").innerHTML = year+"-"+month+"-"+day;
    

    You could do this or use Moment.js

    var NowMoment = moment("OCT 19,2016");
    var eDisplayMoment = document.getElementById('displayMoment');
    eDisplayMoment.innerHTML = NowMoment.format('YYYY-M-D');