MySQL 中 Date 转换
看我一张图,胜写10行码!
从页面获取 String
类型,在 entity 的类中需要转为 java.util.Date
:
1 2 3 4 5 6 7 8 9 10
| public class Stu { private Integer stuId; private String stuName; private Integer stuAge; private java.util.Date stuBirthday; private String stuHobby; private String pwd; private Integer gId; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @WebServlet(name = "RegistServlet", urlPatterns = "/regist") public class RegistServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... Stu stu = new Stu(); ... stu.setStuBirthday(DateUtils.strToDate(birthday)); System.out.println(stu); ... }
|
从 java 代码中设置 java.util.Date
类型到数据库 java.sql.Date
中:
1 2 3 4 5 6 7 8 9 10 11 12
| public class StuDaoImpl implements StuDao { @Override public boolean regist(Stu stu) throws Exception { Connection connection = ConnUtils.getConnection(); String sql = "..."; PreparedStatement prepareStatement = connection.prepareStatement(sql); ... prepareStatement.setDate(3, DateUtils.utilToSql(stu.getStuBirthday())); ... return prepareStatement.executeUpdate() == 1; } }
|
DateUtils
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class DateUtils { private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-DD");
public static java.util.Date strToDate(String date) { try { return simpleDateFormat.parse(date); } catch (ParseException e) { e.printStackTrace(); } return null; }
public static java.sql.Date utilToSql(java.util.Date date) { return new java.sql.Date(date.getTime()); } }
|