Search code examples
javadatetimegregorian-calendarjava-calendar

applying Gregorian Calendar in JAVA


import  java.util.GregorianCalendar ;
public class MyCalendar extends  GregorianCalendar  {
public static void main(String[] args) {
           MyCalendar a = new MyCalendar();
           System.out.println(a.getCurrenttime());
}

public String getCurrenttime(){
     String time= YEAR+"-"+(MONTH+1)+"-"+DATE+"-"+HOUR+"-"+MINUTE+"-"+SECOND; 
     return time;}}

However, it always show the same time. What have I done wrong.

P.S. it is intended not to use command like gettime() directely. The string should remain there.


Solution

  • By using YEAR, MONTH... and so on, Here you are accessing static fields inherited from the GregorianCalendar class. However, you have to access the fields of your Calendar using these variables in somthing like this :

         public String getCurrenttime(){
    
        String time= this.get(YEAR)+"-"+(this.get(MONTH)+1)+"-"+
                this.get(DATE)+"-"+this.get(HOUR_OF_DAY)+"-"+this.get(MINUTE)+"-"+this.get(SECOND);
        return time;
    }