JAVA: how to add extra time to timestamp
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 to share
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 to share
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 to share