Home > Net >  Is this the right code to reuse date and time method? Because I reuse it in three activities
Is this the right code to reuse date and time method? Because I reuse it in three activities

Time:06-24

I have created DateTime.java class like this:

public class DateTime {


public String date() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.DATE)  "/"   calendar.get(Calendar.MONTH)   "/"   calendar.get(Calendar.YEAR);
}

public String time() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.HOUR)   ":"   calendar.get(Calendar.MINUTE);
}

   }

in all three activities I get the date and time like this:

        DateTime dateTime = new DateTime();
            dbHelper.insertNote(note, dateTime.date(), dateTime.time(), System.currentTimeMillis());
            finish();

Is there any problem with the DateTime class implementation?

CodePudding user response:

Instead of creating a new instance of DateTime everytime make your both methods as static. In this way, you will be able to access them directly without creating a new object of DateTime class. This will have negligible effect on your memory because the class is very simple, but it is a good thing to do so that you can use these methods without filling your memory

public class DateTime {

   public static String date() {
       Calendar calendar = Calendar.getInstance();
       return calendar.get(Calendar.DATE)  "/"   calendar.get(Calendar.MONTH)   "/"   calendar.get(Calendar.YEAR);
   }

   public static String time() {
       Calendar calendar = Calendar.getInstance();
       return calendar.get(Calendar.HOUR)   ":"   calendar.get(Calendar.MINUTE);
   }

}

to use:

dbHelper.insertNote(note, DateTime.date(), DateTime.time(), System.currentTimeMillis());
  • Related