Luo Hao

Java各时间类的转换

rehoni / 2020-10-13


LocalDateTime和String的转换

// LocalDateTime转为String
String string = LocalDateTime.now().format(new DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"));
// String转为LocalDateTime
String time = "2020-07-08 14:41:50.238473";
LocalDateTime parse = LocalDateTime.parse(time, new DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"));

java.util.Date和String的转换

SimpleDateFormat格式化进行转换

 // java.util.Date转换String
 DateFormat dateFormat = new SimpleDateFormat("dd-MM-yy:HH:mm:ss");
 Date date = new Date();
 String dateStr = dateFormat.format(date);
 // String转换java.util.Date
 try {
     DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyy");
     Date date = dateFormat.parse(dateStr);
 } catch (ParseException e) {
     e.printStack();
 }

java.sql.Timestamp和String的转换

与java.util.Date和String的转换类似,都是通过SimpleDateFormat格式化进行转换,不展开代码细讲。

java.util.Date和java.sql.Timestamp的转换

 //Date转换Timestamp
 Timestamp timestamp = new Timestamp((new Date()).getTime());
 //Timestamp转换Date,二者是父子关系,可以直接赋值,自动转换
 Timestamp timestamp1 = new Timestamp(System.currentTimeMillis());
 Date date = new Date(timestamp1.getTime());

timestamp的比较

beforeafter函数,可以参考源码内的实现,compareTo接口。

 Timestamp a = Timestamp.valueOf("2018-05-18 09:32:32");
 Timestamp b = Timestamp.valueOf("2018-05-11 09:32:32");
 if (b.before(a)) {
     System.out.println("b时间比a时间早");
 }

before函数中封装了compareTo函数,在compareTo(Timestamp t)中对传入的Timestamp做比较。通过long thisTime = this.getTime();获取的时间戳进行比较,compareTo(Date u)也可以传入java.util.Date,不过也是对其做Timestamp的转换后调用compareTo(Timestamp t)做的处理。

参考

JAVA比较2个Timestamp类型的时间大小-由此引发的思考