Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Timestamp - Adding five minutes

Tags:

java

looking for some help with a bit of Java code i'm working on, i have the following code which prints out the date and time:

  Date dNow = new Date( ); // Instantiate a Date object   SimpleDateFormat ft = new SimpleDateFormat ("MMM d, yyyy k:mm:ss");  // Time at server 

Result: Mar 15, 2013 10:19:48

I'm creating a javascript counter to work from this number and countdown from 5 minutes. So i need to add 5 minues to the current date time in Java.

So, if the current date time is: Mar 15, 2013 10:19:48

I need to add 5 minutes to Java so that it prints out: Mar 15, 2013 10:24:48

Any ideas?

like image 932
Scott Avatar asked Mar 15 '13 10:03

Scott


People also ask

What is the length of timestamp in java?

It will always be exactly 64 bits long and will typically have a number of leading zeroes.

What does getTime return in java?

getTime() Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. int. getTimezoneOffset()


2 Answers

Instead of starting with

new Date() 

start with

new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5)) 

This will give you a Date instance that represents your required point in time. You don't need to change any other part of your code.

like image 164
Marko Topolnik Avatar answered Sep 27 '22 15:09

Marko Topolnik


Ignoring Dates and focusing on the question.

My preference is to use java.util.concurrent.TimeUnit since it adds clarity to my code.

In Java,

long now = System.currentTimeMillis(); 

5 minutes from now using TimeUtil is:

long nowPlus5Minutes = now + TimeUnit.MINUTES.toMillis(5); 

Reference: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html

like image 20
Alexandre Santos Avatar answered Sep 27 '22 17:09

Alexandre Santos