需求:
从Java获取当前时间存进数据库
实现
// 获取当前时间 LocalDateTime now = LocalDateTime.now(); // 格式化时间 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDateTime = now.format(formatter); // 将字符串解析为LocalDateTime对象 LocalDateTime localDateTime = LocalDateTime.parse(formattedDateTime, formatter); // 将LocalDateTime对象转换为Timestamp对象 Timestamp timestamp = Timestamp.valueOf(localDateTime); //存进MySQL String sql2 = "insert into log(username,name,log_time) values (?,?,?)"; ps = con.prepareStatement(sql2); ps.setString(1,param1); ps.setString(2,param2); ps.setTimestamp(3,timestamp);