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

后端 未结 15 2207
不思量自难忘°
不思量自难忘° 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:18

    To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class test {
        public static void main(String argv[]){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            Date now = new Date();
            String strDate = sdf.format(now);
            System.out.println(strDate);
        }
    }
    

    0 讨论(0)
  • 2020-11-22 15:19

    I would use something like this:

    String.format("%tF %<tT.%<tL", dateTime);
    

    Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.

    0 讨论(0)
  • 2020-11-22 15:19

    Ans:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
    String startTimestamp = start.format(dateFormatter);
    
    0 讨论(0)
  • 2020-11-22 15:20

    try this:-

    http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
    

    or

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println(dateFormat.format(cal.getTime()));
    
    0 讨论(0)
  • 2020-11-22 15:20

    The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion

    0 讨论(0)
  • 2020-11-22 15:22

    java.text (prior to java 8)

    public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        };
    };
    
    ...
    dateFormat.get().format(new Date());
    

    java.time

    public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    
    ...
    dateTimeFormatter.format(LocalDateTime.now());
    
    0 讨论(0)
提交回复
热议问题