What is the correct way to get the device date?

2

This is a relatively simple question, but it has broken my mind a lot. I need to get the date and time at a certain point in my application's execution, but I do not know which is the most recommended way to do this. In some places, I have seen suggest using the Time API, in others I was told to use Calendar , others told me to use Date , some indicated me to format output using SimpleDateFormat , others said SimpleDateFormat can have performance problems and told me to use DateFormat ... anyway, I'm lost. I do not know where to start. In this situation, which path is the most appropriate?

    
asked by anonymous 04.06.2015 / 07:09

2 answers

5

System.currentTimeMillis() is most effective if your primary concern is performance. Date() must be close in terms of performance because it is just an encapsulator of a value (long) in milliseconds.

The Calendar class is comparatively slower and much more complex resulting from the need to deal with all the inherent characteristics of the date and time (leap years, summer / winter time adjustments, different time zones, etc.).

In conclusion:

  • If the main concern is performance then it suggested System.currentTimeMillis () '.
  • To perform calculations or to format dates for the user would suggest the use of the Calendar class because of its flexibility. It has a getInstance method that returns an implementation according to the settings (region / location) of the device. For example, if the device is configured for a location in Europe or America will return a calendar Gregorian.

    Its use is simple:

    Calendar c = Calendar.getInstance(); 
    Date data = c.getTime();
    

    The method getInstance returns a 'calendar' initialized with the date and time in accordance with the local settings of the device.

Finally, Time class has been declared obsolete since API Level 22 and the earlier page of the API itself warned against its use due to various problems that had been detected and recommended using the Calendar or GregorianCalendar class.

  

This class has a number of issues and it is recommended that   GregorianCalendar is used instead.

    
04.06.2015 / 12:27
1

In practice use all these classes, in this example it generates two day and time strings, with the format for 02-03-2018 and string hour 22:21:30

    Calendar calendar = Calendar.getInstance();//cria o obj calendar e atribui a hora e data do sistema
    Date data = calendar.getTime();//transforma o obj calendar em obj Date

    SimpleDateFormat sddia = new SimpleDateFormat("dd-MM-yyyy");//cria um obj de formatação de data
    SimpleDateFormat sdhora = new SimpleDateFormat("HH:mm:ss");//cria um obj de formatação de hora
    String dia = sddia.format(data);//gera a string final formatada no estilo "dd-MM-yyyy"
    String hora = sdhora.format(data);//gera a string final formatada no estilo "HH:mm:ss"
    
03.03.2018 / 02:23