Skip to content
Advertisement

Can I add seconds to current date without using Calendar Library in Java?

I want to get the current time in Java, and now I want to add 15 seconds above the time. Can I do this with a library other than the Calendar library in java?

import java.util.Calendar;
    public class Test {
       public static void main(String[] args) {
          Calendar calendar = Calendar.getInstance();
          System.out.println("current date = " + calendar.getTime());
          calendar.add(Calendar.SECOND, 15); // Add 15 seconds to current date
          System.out.println("Updated Date = " + calendar.getTime());
       }
    }

Advertisement

Answer

Indeed! The java.time package was added because the Calendar and Date classes were insufficient. Something with LocalDateTime perhaps. Like,

LocalDateTime now = LocalDateTime.now();
System.out.println("current date = " + now);
System.out.println("Updated Date = " + now.plusSeconds(15));
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement