How to print time up to 6 digits of precision for seconds value

前端 未结 4 726
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-01 23:58

I have a value in column which is of type timestamp. Lets say I have a value 2007-05-04 08:48:40.969774

Now, when trying to fetch the value from the

4条回答
  •  天涯浪人
    2021-01-02 00:40

    Dealing with nanoseconds in Java is not trivial. I cannot see any elegant solution other than dealing with them in a separate way (format date and time with SimpleDateFormat and nanoseconds with DecimalFormat), for example, like in the following example:

    
    package test;
    
    import java.sql.Timestamp;
    import java.text.DateFormat;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    
    public class Main {
    
      public static void main(String[] args) {
        Main m = new Main();
        m.start();
      }
    
      private void start() {
        long time = System.currentTimeMillis();
        Date d = new Date(time);
        Timestamp t = new Timestamp(time);
        t.setNanos(123456789);
        System.out.println(d);
        System.out.println(t);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'.'");
        NumberFormat nf = new DecimalFormat("000000000");
        System.out.println(df.format(t.getTime()) + nf.format(t.getNanos()));
      }
    }
    
    

    The output produced is (in my country, my locale):

    Mon Apr 09 16:27:27 CEST 2012
    2012-04-09 16:27:27.123456789
    2012-04-09 16:27:27.123456789
    

提交回复
热议问题