在json中添加事件时,日期格式化是错误的

时间:2017-03-09 03:45:10

标签: json spring

我正在尝试在日历中显示事件,我将值设置为json 设置json日期属性中的值时设置为" 3月1,2017"但我需要将日期设置为2017-03-01的json值。

这里我给出了我的编码

控制器:

@RequestMapping(value = { "/calender_view_get_json" }, method = RequestMethod.GET,headers = "Accept=*/*", produces = "application/json")
    public @ResponseBody String viewCalenderJson(Model model, HttpSession session ,HttpServletRequest request,HttpServletResponse response) throws ParseException {
        if(request.getRequestedSessionId()!=null&&!request.isRequestedSessionIdValid()){
            return "";
        }
        else{

            User user=(User) session.getAttribute("loggedinuserOb");
            List<calendar> events=teacherService.getLessonPlanByTeacherId(user.getId());
            Gson gson = new Gson();
           String jsonEvents = gson.toJson(events);


            return jsonEvents;
        }
    }

数据库访问:

public List<calendar> getLessonPlanByTeacherId(int t_id){


        List<LessonPlan> lst=new ArrayList<LessonPlan>();
        List<calendar> cl_list=new ArrayList<calendar>();
        try {
        Session session=sessionFactory.openSession();
        Query q=session.createSQLQuery("select * from sts_class_lesson_plan where teacher_id=(select id from sts_teachers where app_user_id="+t_id+") and month(created_on)=month(utc_date())");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<Object[]> rows=q.list();
        for (Object[] row : rows) {
            calendar cl=new calendar();



            cl.setStart((Date)row[1]); //May be problem in this line

            cl.setTitle((String)row[8]);
            cl_list.add(cl);
        }

        session.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }


        return cl_list;
    }

服务

public List<calendar> getLessonPlanByTeacherId(int t_id){
        //List<calendar> cal_list=new ArrayList<calendar>();

        List<calendar> cl_list=teacherDAO.getLessonPlanByTeacherId(t_id);
return cl_list;
    }

在datebase类中我获取数据库值并将其设置为Model类日历

当前获取日期格式:2017年3月1日 所需日期格式:2017-03-01

任何人都可以帮我搞定这个

1 个答案:

答案 0 :(得分:1)

实现您正在寻找的内容的方法是在您的控制器方法viewCalenderJson中用以下内容替换您的Gson实例构造:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();