JAVA: how to add extra time to timestamp

Sorry im new for java, may I know how can I add extra time here?

SimpleDateFormat timestampFormat    = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
String currTimestamp  = timestampFormat.format(new Date());
System.err.println("currTimestamp=="+currTimestamp); //  2014/10/17 14:31:33

      

+3


source to share


4 answers


You can use Calender for this.

Calendar calendar=Calendar.getInstance(); // current time
System.out.println(calendar.getTime());
calendar.add(Calendar.MINUTE,3); // add 3 minutes to current time
System.out.println(calendar.getTime());

      



Output:

Fri Oct 17 12:17:13 IST 2014
Fri Oct 17 12:20:13 IST 2014

      

+6


source


As a comparison using Java 8 new time API ...

LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
ldt = ldt.plusMinutes(3);
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));

      



Or if you cannot use Java 8, you can use JodaTime API

SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dt = DateTime.now();
System.out.println(timestampFormat.format(dt.toDate()));
dt = dt.plusMinutes(3);
Date date = dt.toDate();
System.out.println(timestampFormat.format(dt.toDate()));

      

+4


source


The Calander class has several useful methods for this. If you want to still use Date it self, add 3000 milliseconds to the current time.

String resultTime = timestampFormat.format(new Date(new Date().getTime() + 3000));

      

+2


source


Better to use a class Calendar

instead of using a deprecated class Date

:

Pull the instance Calendar

:

Calendar c = Calendar.getInstance();

      

Add 3 minutes to the current calendar time:

c.add(Calendar.MINUTE, 3);

      

Format the new calendar time:

SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
String currTimestamp = timestampFormat.format(c.getTime());
System.err.println("currTimestamp==" + currTimestamp);

      

+2


source







All Articles