Date class and Calendar class in Java

Date class and Calendar class in Java


There are two commonly used classes related to time in Java: Date class and Calendar class. They didn't know anything when they started to do the topic. They got some basic understanding by consulting the information on the Internet. (In fact, you can also check the Java API, This is a very effective learning method, and this awareness will be strengthened in the future).

example

The java.util package contains a class GregorianCalendar, which can be used to obtain the year, month, and day of a certain date. Its parameterless construction method creates an instance of the current date, and there are other corresponding methods. Encapsulate a class of ShowDate, including two methods:
(1) Display the current year, month, and day;
(2) Use the public void setTimeInMillis(long millis) method to set a specific value from January 1, 1970 time. Set this value to 1234567898765L, and then display the year, month, and day.

Displaying the current year, month, and day and calculating the specified date according to a certain benchmark can directly use the existing Calendar class in Java. For specific information, please refer to the Java Calendar class , which contains many attributes and methods of the Calendar class. The main ones are:Calendar date=Calendar.getInstance(), The meaning is to create a calendar object, and then call the corresponding method according to the meaning of the question.

Code

Main class NewMain

public class NewMain {
    
    
    public static void main(String[] args) {
    
    
    	ShowDate phc=new ShowDate();
        phc.printCurrentDate();
        phc.setTimeInMillis(1234567898765L);
 	}
}

Function class ShowDate

import java.util.Calendar;

public class ShowDate {
    
    
    
    public  void printCurrentDate(){
    
    
        Calendar now = Calendar.getInstance(); //获取一个日历对象
        System.out.println("当前年: " + now.get(Calendar.YEAR)); //调用get方法,获取当前年、月、日
        System.out.println("当前月: " + (now.get(Calendar.MONTH)+1) +"");
        System.out.println("当前日: " + now.get(Calendar.DAY_OF_MONTH));
    }
    
    public void setTimeInMillis(long millis){
    
    
        Calendar date=Calendar.getInstance();
        date.setTimeInMillis(millis); //给定的long 值设置成为基准时间值
        System.out.println("指定日期的年"+date.get(Calendar.YEAR));//调用get方法,获取以基准时间为标准的当前年、月、日
        System.out.println("指定日期的月"+date.get(Calendar.MONTH));
        System.out.println("指定日期的日"+date.get(Calendar.DAY_OF_MONTH));
    }
}

There are many important and commonly used classes in Java. It is necessary to frequently refer to the usage by memorization and use it in the code. This is a very important step to learn Java well.

Guess you like

Origin blog.csdn.net/m0_46772594/article/details/106029162