How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

后端 未结 15 2333
不思量自难忘°
不思量自难忘° 2020-11-22 15:05

The code below gives me the current time. But it does not tell anything about milliseconds.

public static String getCurrentTimeStamp() {
    SimpleDateForm         


        
15条回答
  •  不知归路
    2020-11-22 15:09

    The easiest way was to (prior to Java 8) use,

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    

    But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.

    So in Java 8 something like below will do the trick (to format the current date/time),

    LocalDateTime.now()
       .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    

    And one thing to note is it was developed with the help of the popular third party library joda-time,

    The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.

    But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.

    Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project

    Anyway having said that,

    If you have a Calendar instance you can use below to convert it to the new java.time,

        Calendar calendar = Calendar.getInstance();
        long longValue = calendar.getTimeInMillis();         
    
        LocalDateTime date =
                LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
        String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    
        System.out.println(date.toString()); // 2018-03-06T15:56:53.634
        System.out.println(formattedString); // 2018-03-06 15:56:53.634
    

    If you had a Date object,

        Date date = new Date();
        long longValue2 = date.getTime();
    
        LocalDateTime dateTime =
                LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
        String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
    
        System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
        System.out.println(formattedString);     // 2018-03-06 15:59:30.278
    

    If you just had the epoch milliseconds,

    LocalDateTime date =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());
    

提交回复
热议问题