将request.getparameter()结果转换为日期

She*_*n.W 0 jsp date request simpledateformat

我有一个jsp页面,它采用输入类型日期.在servlet中我使用request.getParameter()和SimpleDateFormat来获取用户输入的日期.

我的问题是我只想得到日,月和年但我也得到时间,这意味着当我显示我以这种格式显示的日期时 - 日名:月:月日:时间:年,但我只有想要显示 - 年份:月份:月份日期.

这就是我所做的:

Date startDate=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("startDate")); //get the parameter convert it to a data type Date.

out.println(startDate); //Display the date
Run Code Online (Sandbox Code Playgroud)

这里似乎有什么问题?

感谢您的时间.

Ani*_*rni 5

您的问题是您将Date(java.util.Date)对象传递给println方法.println 在日期对象内部调用Date#toString(),这会产生您不想要的格式.

如果您的问题在servlet中,那么您需要Date对象

String startDateStr = request.getParameter("startDate");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//surround below line with try catch block as below code throws checked exception
Date startDate = sdf.parse(startDateStr);
//do further processing with Date object
......
.... 
Run Code Online (Sandbox Code Playgroud)

如果要打印日期,则可以 根据格式将日期转换为String,并将该字符串传递给println方法

out.println(sdf.format(startDate)); //this is what you want yyyy-MM-dd  
Run Code Online (Sandbox Code Playgroud)

也可以看看