javadatedatetimetimestamp

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"


How to get timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Timestamp());

This is what I have, but Timestamp() requires an parameters...


Solution

  • // Get the current date and time
    LocalDateTime now = LocalDateTime.now();
    
    // Define the format
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // Format the current date and time
    String formattedNow = now.format(formatter);
    
    // Print the formatted date and time
    System.out.println("Current Timestamp:" + formattedNow);
    

    Legacy Answer

    Replace

    new Timestamp();
    

    with

    new java.util.Date()
    

    because there is no default constructor for Timestamp, or you can do it with the method:

    new Timestamp(System.currentTimeMillis());