MySQL中的date类型如果用hibernate反向生成,则对应java中的Date类型,datetime类型对应java中的Timestamp 类型。
timestamp与date区别:
Date表示特定的瞬间,精确到毫秒,而Timestamp类型由 java.util.Date 和单独的毫微秒值组成,只有整数秒才会存储在 java.util.Date 组件中,小数秒(毫微秒)是独立存在的。传递 java.util.Date 类型的值时,Timestamp.equals(Object) 方法永远不会返回 true(就像判断一个float类型是否等于0一样,只能近似判断,无法用等号直接判断),因为日期的毫微秒组件是未知的。
新建一个格式为:yyyy-MM-dd HH:mm:ss的Timestamp 类型的当前时间:
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(currentTime);
System.out.println(time);
新建一个格式为:yyyy-MM-dd HH:mm:ss的Date 类型的当前时间:
Date currentTime = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date registerTime = sdf1.format(currentTime );
用一个Date类型的当前时间减轻一个String类型的Date时间,得出相差的天数:
Date currentTime = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createTime = "2014-12-2 19:54:40";
Date registerTime = sdf1.parse(createTime);
long l=currentTime.getTime()-registerTime.getTime(); //单位为毫秒,除以1000变成秒,再除以一天24小时得到相差天数
long day=l/(24*60*60*1000);
用一个Timestamp类型的当前时间减轻一个String类型的Date时间,得出相差的天数:
Timestamp currentTime = new Timestamp(System.currentTimeMillis());
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String createTime = "2014-12-2 19:54:40";
Date registerTime = sdf1.parse(createTime);
long l=currentTime.getTime()-registerTime.getTime();
long day=l/(24*60*60*1000);
从数据库中拿出一个datetime类型的时间数据与当前时间做比较,求出相差天数:
String userAccountSql="select create_time from scpn_user where user_id="+userAccountId;
Map userAccountMap=(Map)jdbcTemplate.queryForMap(userAccountSql);
String createTime= (String)userAccountMap.get("create_time").toString();
Date currentTime = new Date();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date registerTime = sdf1.parse(createTime);
long l=currentTime.getTime()-registerTime.getTime(); long day=l/(24*60*60*1000);