Search code examples
javajavascriptspring-mvcstruts-1

Formatting a date as a string, from bean to javascript


In my bean, I'm formatting a date as a string:

 public void setStrDate(Date dte) {
    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    this.strDate = df.format(dte);
 }

In my js file, I'm grabbing the data:

 $('#content').data("myDate", <c:out value="${myBean.strDate}"/>);

And in my js, displaying the data:

 $('#sideBar').find("p[class=stat]").append($('#content').data("myDate"));

The date comes over as 10/10/2014. I even see it in the developer tools this way: $('#content').data("myDate", 10/10/2014);

But on the webpage, it shows up as 0.0004965243296921549

How can I format this?


Solution

  • You need to put quotes around your date when you output it. Make it read:

     $('#content').data("myDate", "<c:out value="${myBean.strDate}"/>");
    

    Why is it resulting in 0.0004965243296921549

    10/10/2014 is actually being evaluated as math, 10/10 = 1 -> 1/2014=0.0004965243296921549


    *if this code "<c:out value="${myBean.strDate}"/>" is making your editor flip out about the quotes then you can use single quotes as well '<c:out value="${myBean.strDate}"/>'