[Java] How to use Calendar class and Date class

Programming study diary

October 30, 2020 I dealt with the Calendar class in Yesterday's article, but I will summarize it because it is different from the Date class and I did not understand how to use it.

Difference between Calendar class and Date class

The Calendar class and Date class can handle Java dates. It is the same in that it handles dates, but it has different uses.

Specifically, the Calendar class can perform arithmetic processing on dates and times, and can calculate date values </ b>. The Date class has an elapsed time since 00:00 on January 1, 1970, and is used to get the specified date and time </ b>. The sample code is shown below (the method is not explained this time).

How to use the Calendar class

import java.util.Calendar

public class Main {
  public static void main(String[] args) throws Exception {
    Calendar calendar = Calendar.getInstance();
    System.out.println(calendar.get(Calendar.YEAR) + "Year" + calendar.get(Calendar.MONTH)+ "Moon" + calendar.get(Calendar.DATE) + "Day" );
  }
}

Execution result


October 30, 2020

How to use Date class

import java.util.Date;
 
public class Main {
  public static void main(String[] args) throws Exception { 
    Date date = new Date();
    System.out.println(date);
  }
}

Execution result


Fri Oct 30 10:43:58 UTC 2020

How to convert from Calendar class to Date class

You can convert from Calendar class to Date class by getting the current time for Calendar type variable using getTime method and setting it in Date type variable.

import java.util.Date;
import java.util.Calendar;
 
public class Main {
  public static void main(String[] args) throws Exception {
    //Convert from Calendar class to Date class
    Calendar calendar = Calendar.getInstance();
    Date date = new Date();
        
    date = calendar.getTime();
    System.out.println(date);
  }
}

Execution result


Fri Oct 30 10:43:58 UTC 2020

How to convert from Date class to Calendar class

You can convert from Date class to Calendar class by using setTime method to set date and time.

import java.util.Date;
import java.util.Calendar;
 
public class Main {
  public static void main(String[] args) throws Exception {
    //Convert from Date class to Calendar class
    Date date = new Date();
    Calendar calendar = Calendar.getInstance();
        
    calendar.setTime(date);
    System.out.println(cl.getTime().toString());
  }
}

Execution result


Fri Oct 30 10:43:58 UTC 2020

References

[Introduction to Java] Summary of how to use and convert Date and Calendar Date ⇔ Calendar conversion method

Recommended Posts