java向MySQL插入当前时间的方法

第一种:

将java.util.Date类型的时间转成mysql数据库识别的java.sql.Date类型时间

注:java.util.Date是java.sql.Date的父类

import java.util.Date;


java.sql.Date time= new java.sql.Date(new Date().getTime());

第二种:

利用System.currentTimeMillis()获取当前系统时间

import java.sql.Date

long l = System.currentTimeMillis();
Date time=new Date(l);

System.currentTimeMillis()产生一个当前的毫秒,这个毫秒其实就是自1970年1月1日0时起的毫秒数,Date()其实就是相当于Date(System.currentTimeMillis());因为Date类还有构造Date(long date),用来计算long date秒与1970年1月1日之间的毫秒差。

得到了这个毫秒数,我们自己也可以算起现在的年月日周时,但是这不是我们去计算的,因为有Calendar。Calendar最终出的结果就是年月日周时时区。
System.currentTimeMillis() 获得的是自1970-1-01 00:00:00.000 到当前时刻的时间距离,类型为long
String.valueOf(System.currentTimeMillis()) 这个语句可转为以下的型式:
long ct = System.currentTimeMillis();
String t = String.valueOf(ct);
其实上面的String t就相当于 ct+"",转为字符串格式

实例:格式化时间

import java.sql.Date

long l = System.currentTimeMillis();
Date time=new Date(l);
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(time));

运行结果:

2017-02-18 16:48:02

原文地址:https://www.cnblogs.com/jonsnow/p/6413493.html