Search code examples
javadategetreturn

Return time to another class


I'm trying to collect the minute of the hour. This seems to work in this class. Now I want to use intTime in an other class for some calculations. How do I return intTime. I tried to use the same principles when returning a attribute of an instance, but time is not related to any of the objects I use. Is getIntTime viable?

import java.text.SimpleDateFormat;
import java.util.*;

public class Time extends Database{
    public Time(){
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
        String stringTime = sdf.format (cal.getTime());

        int intTime = 0;

        stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
        intTime = Integer.parseInt(stringTime);
    }

    public String getStringTime() {
        return intTime;
    }

    public static void main (String[] args) {
    }
}

Solution

  • You need to define the intTime as a class member. In your code, the intTime is 'living' only inside the constructor.

    import java.text.SimpleDateFormat;
    import java.util.*;
    
    public class Time extends Database{
        // class member defined in the class but not inside a method.
        private int intTime = 0;
        public Time(){
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
            String stringTime = sdf.format (cal.getTime());
    
            // vars defined here, will be gone when method execution is done.
    
            stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
    
            // setting the intTime of the instance. it will be available even when method execution is done.
            intTime = Integer.parseInt(stringTime);
        }
    
        public String getStringTime() {
            return intTime;
        }
    
        public static void main (String[] args) {
            // code here
        }
    }