问题
I'm using the following code to get the date and time
public class offer extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet offer</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1> sv sugar mills</h1>");
doPost(request,response);
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
java.sql.Date sqlDate=null,ofrmonth=null,ctime=null;
dat="14/02/2013";
try
{
java.util.Date date=new SimpleDateFormat("dd/MM/yyyy").parse(dat);
//ctime=new java.sql.Date(date.getTime());
sqlDate = new java.sql.Date(date.getTime());
out.println(sqlDate);
out.Println(ctime);
}
catch(Exception e)
{
out.println(e);
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here, the util.Date variable date is displayed as "Thu Feb 14 00:00:00 IST 2013". So I get the sql.Date easily as "2013-02-14". Also, I want to get the time from it. In the ctime variable I want to get the time and display it. The format should be 24hours format. But I don't know how to get it.
I've used some functions like getHours() and getDate(), but I couldn't found the solution. Can someone help me to get the time. Thanks in advance
I need the time as 00:00:00 (hh:mm:ss)
回答1:
Try this:
Calendar c = Calendar.getInstance();
c.setTime(sqlDate);
System.out.println(c.get(Calendar.HOUR));
System.out.println(c.get(Calendar.MINUTE));
System.out.println(c.get(Calendar.SECOND));
Unless you set a time zone for the Calendar
object the above returns time in your machine's time zone.
And if you want a single String
in the form of HH:mm:ss
as output, you can use a SimpleDateFormat as pointed out by @zvzdhk.
Snippet:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(sqlDate));
Note that TimeZone.getTimeZone
allows argument like "GMT+5:30"
, "PST"
etc. Read the documentation for more.
来源:https://stackoverflow.com/questions/14868537/servlet-get-date-and-time