problem with the use of java calendar

0

I'm trying the class Calendar in java, I made a class that returns the current time and minutes, when I ask for the first time the current minutes work, but when I do the second the minutes do not change, for example I execute the method to 12:35, then I execute it at 12:36 and even then it keeps returning 35 as the current minute.

this is the code:

import java.util.Calendar;

public class HoraActual
{
  static Calendar now = Calendar.getInstance();

  public static int getHora(){
     return now.get(Calendar.HOUR);
  }

  public static int getMinutos(){
    return now.get(Calendar.MINUTE);
  }
}
    
asked by Eduard Damiam 24.08.2017 в 06:22
source

2 answers

5

The Calendar class usually only saves you the time and date that they were at the time the calendar object was created. If you want to obtain the current time and date at another time, you can use the setTimeInMillis() method as follows:

//Crear un nuevo objeto Calendar
Calendar cal = Calendar.getInstance();
//Mostrar la hora actual en pantalla
System.out.println("Hora actual: "+cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));

/* Tiempo después... */
//Actualizar la hora mostrada en el calendario
cal.setTimeInMillis(System.currentTimeMillis());
//Mostrar la hora actual en pantalla
System.out.println("Hora actual: "+cal.get(Calendar.HOUR)+":"+cal.get(Calendar.MINUTE));
    
answered by 24.08.2017 / 06:38
source
4

Your variable now only gets a value at the beginning that is why it will always have the same value, you have to give it a Calender.getIntance to your variable again now to take the current time again. Example:

import java.util.Calendar;

public class HoraActual
{
  static Calendar now = Calendar.getInstance();

  public static int getHora(){
     return now.get(Calendar.HOUR);
  }

  public static int getMinutos(){
    return now.get(Calendar.MINUTE);
  }
  public static void refresh(){
    this.now = Calendar.getInstance();
  }

}

Once the refresh method is called, it will have the current date again.

    
answered by 24.08.2017 в 07:04