java.util.date与java.sql.date的转化

一,util.Date转化成String

Java代码

  1. Date date=Calendar.getInstance().getTime();
  2. Format format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  3. System.out.println(format.format(date));
Date date=Calendar.getInstance().getTime();
Format format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(format.format(date));


二,util.Date转化sql.Date

Java代码

  1. Date date=Calendar.getInstance().getTime();
  2. java.sql.Date sqldate = new java.sql.Date(date.getTime());
Date date=Calendar.getInstance().getTime();
java.sql.Date sqldate = new java.sql.Date(date.getTime());


操作

Java代码

  1. preparedStatement.setDate(1, sqldate );
preparedStatement.setDate(1, sqldate );


但是这种方式,会造成日期后面的时分秒丢失。可以换成:

Java代码

  1. java.sql.Date time = new java.sql.Date(date.getTime());
  2. java.sql.Timestamp timestamp = new java.sql.Timestamp(time.getTime());
java.sql.Date time = new java.sql.Date(date.getTime());
java.sql.Timestamp timestamp = new java.sql.Timestamp(time.getTime());


操作

Java代码

  1. preparedStatement.setTimestamp(1, timestamp);
preparedStatement.setTimestamp(1, timestamp);


读取

Java代码

  1. java.util.Date date = new java.util.Date(resultSet.getTimestamp(1).getTime());

你可能感兴趣的:(java)