已知在数据库中保存的时间是String类型,现在要求出两个时间间隔,故通过求出时间的毫秒数值,然后相减,即得到两个时间的间隔。
1.日期转换为毫秒
思路:首先需要将String型的时间转换为以日期型的时间,然后利用getTime()得到时间的毫秒数值。
public class Test {
public static void main(String[] args) {
String date = "2017-01-18 16:50:50";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//要转换的日期格式,根据实际调整""里面内容
try {
long dateToSecond = sdf.parse(date).getTime();//sdf.parse()实现日期转换为Date格式,然后getTime()转换为毫秒数值
System.out.print(dateToSecond);
}catch (ParseException e){
e.printStackTrace();
}
}
}
结果:1484729450000
2.毫秒转换为日期
public class Test {
public static void main(String[] args) {
long sd=1484729450000L;
Date dat=new Date(sd);
GregorianCalendar gc = new GregorianCalendar(); //标准阳历
gc.setTime(dat); //利用setTime()设置其时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sb=sdf.format(gc.getTime()); //利用format()将日期类型转换为String类型。
System.out.println(sb);
}
}
结果:2017-01-18 16:50:52