关于java时间类型和格式化到微秒问题

常规的问题此处略,因为网络上到处都是,这里主要讨论三个问题:

1.数据库的时间戳类型(含微秒)对应java的什么类型

java的常见时间类型比较多:

  • java.util.Date
  • java.sql.Date
  • java.sql.Timestamp
  • java.util.Calendar
  • java.time.LocalDate
  • java.time.LocalTime
  • java.time.LocalDateTime
  • java.time.Instant

除了这些,还有许多不常用的java.time类型,例如Year,Month。

以上列出的类型中,只有红色部分可以精确到微秒。

我们常用的Date,Calendar并不能精确到微秒。

所以为了能够显示数据库中微秒,在使用mybatis的时候,需要把字段类型映射为java.sql.Timestamp。

当然也可以映射为其它类型,例如LocalDateTime,Instant,不过需要自己添加mybatis的typeHandler,以便把类型转为适当的类型。

2.java.sql.Timestamp到底是不是包含了微秒

看具体情况,这是因为Timestamp本身有多个初始化方式:

public Timestamp(int year, int month, int date,int hour, int minute, int second, int nano)  -- 可以到微秒,但是从jdk1.8就被标注为过时,这是因为有异常风险

public Timestamp(long time)  time是毫秒,不支持微秒

public void setTime(long time)  time是毫秒,不支持微秒

public static Timestamp valueOf(String s)   -- 可以支持微秒,但对s有格式要求

public static Timestamp valueOf(LocalDateTime dateTime) --可以支持微秒

public static Timestamp from(Instant instant)   -- 可以支持微秒,这是因为Instant类型支持到纳秒

3.如何格式java的时间类型到微秒

使用SimpleDateFormat是无法格式化到微秒的,所以网络上说SimpleDateFormat格式化到微秒,那是错误的

只能使用java.time.format.DateTimeFormatter才可以格式化出微秒

以下示例如何创建一个包含纳秒的时间,并格式化输出:

/**
     * 格式化到微秒,必须配合 DateTimeFormatter
     * @param time
     * @return
     */
    private String formatTo(Timestamp time) {
        String format="yyyy/MM/dd HH:mm:ss.SSSSSS";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
        LocalDateTime now=LocalDateTime.ofInstant(time.toInstant(), ZoneId.systemDefault());
        return now.format(formatter);
        //SimpleDateFormat form=new SimpleDateFormat(format);
        //return form.format(time);
    }

public static void main(String[] args) {
        TestTimestamp t=new TestTimestamp();
        Timestamp ts2=Timestamp.valueOf("2024-02-04 12:39:45.898777");
        System.out.println(t.formatTo(ts2));
    }

 

posted @ 2024-02-03 13:40  正在战斗中  阅读(101)  评论(0编辑  收藏  举报