Java Data Type How to - Add one minute each method is called








Question

We would like to know how to add one minute each method is called.

Answer

import java.text.SimpleDateFormat;
import java.util.Calendar;
/*from   w  w w .  j  av  a  2s  .  c  om*/
public class Main {
  public static void main(String[] args) {

    Test g = new Test();
    System.out.println("The time is now: " + g.currentTime());
    System.out.println("The time is now: " + g.currentTime());
    System.out.println("The time is now: " + g.currentTime());
    System.out.println("The time is now: " + g.currentTime());
  }
}

class Test {
  private int minutesToAdd = 0;
  private Calendar cal = Calendar.getInstance();
  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

  public String currentTime() {
    cal.add(Calendar.MINUTE, minutesToAdd++);
    return sdf.format(cal.getTime());
  }
}

The code above generates the following result.