1.调用服务,计算时间长度,其他服务给传的时间是 秒,要求存入数据库格式为hh:MM:ss
例如:7000秒 计算时分秒就为 01:56:40
public static String getSecondString(String str) {
Integer second = Integer.valueOf(str);
String h1 = null ;
String m1 = null ;
String s1 = null ;
if (second < 60) {
return "00" + ":" + "00" + str;
}
if (60 <= second && second < 3600) {
Integer m = second / 60;
if(0 <= m && m < 10){
m1 = "0"+m;
}else{
m1 = m.toString();
}
Integer s = second % 60;
if(0 <= s && s < 10){
s1 = "0"+s;
}else{
s1 = s.toString() ;
}
return "00" + ":" + m1 + ":" + s1;
}
if (second >= 3600) {
Integer h = second / 3600;
if(0 <= h && h < 10){
h1 = "0"+h;
}else{
h1 = h.toString() ;
}
Integer m = (second % 3600) / 60;
if(0 <= m && m < 10){
m1 = "0"+m;
}else{
m1 = m.toString() ;
}
Integer s = (second % 3600) % 60;
if(0 <= s && s < 10){
s1 = "0"+s;
}else{
s1 = s.toString() ;
}
return h1 + ":" + m1 + ":" + s1;
}
return null;
}
2.前端传值为 秒 ,存入数据库为 2020-05-12 17:52:20 ,秒转年月日时分秒 yyyy-MM-dd hh:mm:ss
public static String secondToDateTime(long second) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(second * 1000);//转换为毫秒
Date date = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
String dateString = format.format(date);
return dateString;
}
测试
long second = 1589275403;
String s2 = DateUtils.secondToDateTime(second);
System.out.println(s2);
//打印结果为 2020-05-12 17:23:23
3.数据库的时间格式为datetime,调用其他服务获取到的为date类型时间戳,这个时候直接存这个字段到数据库,格式仍然为2020-05-09 16:53:46
以下做了测试,可供参考
long timeInMillis = Calendar.getInstance().getTimeInMillis();
//打印的结果为1589014425738
log.info("timeInMillis{}",String.valueOf(timeInMillis));
Date date = new Date(timeInMillis);
//打印的结果为 Sat May 09 16:53:45 CST 2020
log.info("date{}",date.toString());
studentEntity.setCreateTime(date);
因为JDBC中有jdbcType有对这些做处理封装的,完全不用担心时间存到数据库的格式问题
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />