search
HomeJavajavaTutorialjava time----detailed introduction to java.util.Calendar

java.util.Calendar

There are several time classes in Java, but as Date is gradually disabled, the methods are slowly added. After removing the cross, the remaining usable functions have been implemented in Calendar, and Calendar's subclass GregorianCalendar is too in-depth in the research of special calendars. We usually do not use this subclass. We can believe that the Calendar class will be the mainstream time class in the future. Let’s take a look at the details of the Calendar class. If there are any mistakes, please correct us.

(1) Instantiation

The Calendar class is an abstract class and cannot be instantiated. There are two ways for this class to obtain a calendar instance:

  Calendar calendar = Calendar.getInstance(TimeZone zone , Locale locale);

By calling the getInstance method, select the default Timezone and Locale attributes to return a calendar. You can also add the parameter Timezone or Locale to select the geographical location. For specific parameters, see java.util.Timezone and java.util. For the two Locale packages, the general default time is the common time and we don’t actually need to change it.

In addition, there is a method that can be instantiated. Nothing surprising, the old Java routine is to use subclasses for instantiation. There is only one subclass of Calendar - GregorianCalendar, which translates to the Gregorian calendar. We will talk about this GregorianCalendar separately in the future. The second way of instantiation is as follows:

Calendar calendar = new GregorianCalendar();


(2) Class variables

The variables in Calendar are basically Defined by final, these variables include all time contents such as year, month, hour, morning and afternoon, etc. I found a lot of them on Baidu. When you want to use this, it is best to look at the API. I will briefly paste a copy here:

calendar.get(Calendar.YEAR);  
calendar.get(Calendar.MONTH); 
// 月份从0开始 calendar.get(Calendar.DAY_OF_MONTH);   
calendar.get(Calendar.DAY_OF_WEEK);  
calendar.get(Calendar.WEEK_OF_YEAR);  
calendar.get(Calendar.WEEK_OF_MONTH);  
calendar.get(Calendar.HOUR);        
// 12小时calendar.get(Calendar.HOUR_OF_DAY); 
// 24小时 calendar.get(Calendar.MINUTE);  
calendar.get(Calendar.SECOND);  
calendar.get(Calendar.MILLISECOND);

These values ​​​​are final variables in the source code of jdk. Since they are The int static final modification means that these variables have an initial value of type int. Indeed, these variables are numbered sequentially in the Calendar class as a range judgment when some functions pass in parameters. Then this situation may occur accidentally, such as the following code:

System.out.println(Calendar.DAY_OF_MOUTH);

The output is 5, although today is not the 5th of this month. This is actually a mistake. In fact, what you output is the initial value 5 of DAY_OF_MOUTH in this class. If you want to represent the date of the current month, you must export the class instance to the object, but in a class where the variables of the class can be directly clicked, This kind of error is very common. The correct method should be obtained using the get() method (calendar is the object of our instance):

System.out.println(calendar.get(Calendar.DAY_OF_MOUTH));

(3) compareTo() after() before() function

compareTo (Calendar othercalendar ), returns an int value. If the time of the object is after the parameter time, it returns a number greater than 0, otherwise it returns a number less than 0. In particular, if the times are the same, it returns 0. I think the implementation of this method may directly return milliseconds. Make a difference (I feel like my guess makes sense...), and use the difference in milliseconds as the return value.
After (Calendar othercalendar), before (Calendar othercalendar), these two functions are also easy to guess. They return a boolean value. The after() function returns a positive value if the time is after the parameter, and the before() function returns a positive value if the time is after the parameter. Previously returned a positive value.

Calendar calendar = Calendar.getInstance();
Calendar calendarother = Calendar.getInstance();
calendarother.add(Calendar.DATE, -20);
if(calendar.after(calendarother))
    System.out.println("after");calendarother.add(Calendar.DATE, 100);if(calendar.before(calendarother))
    System.out.println("before");if(calendar.compareTo(calendarother)>0)
        System.out.println(calendar.getTime()+">"+calendarother.getTime());

The output result is:

after 

  before 

  Sun Jan 11 21:19:49 GMT+08:00 1970>Thu Jan 01 00:00:00 GMT+08:00 1970


(4) get() add() set() setTime() function

In the above example, the function add(int field, int amount) appears. This function is relatively powerful. It can add and subtract the value of the first parameter, thereby modifying the corresponding item in the calendar entity. value.

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
System.out.println(calendar.getTime());
//输出的日期是当前日期的前一天,其他所有的都不变

There is nothing to say about get(int field). Put the value you want to get and display it. That’s it. By the way, getTimeInMillis() returns the number of milliseconds. In actual applications, this number of milliseconds is used There are still quite a few.
The set() method has many ways to input parameters, which can be understood in writing. The setTime() function puts a Date object into it and returns a calendar set according to the Date. Another special thing to note is that the month starts from 0. Setting the month to 0 actually means January, setting it to 1 actually means February. The first day of the week is Sunday, and the 7th day is Saturday.

calendar.get(Calendar.DATE);
calendar.getTimeInMillis();

calendar.set(field, value);
calendar.set(year, month, date);
//月份是从0开始,下同
calendar.set(year, month, date, hourOfDay, minute);
calendar.set(year, month, date, hourOfDay, minute, second);
calendar.setTime(Date date);
//Date对象

(5) getTime() clear() isSet() function

getTime() function returns a time, probably in this format

Sun Jan 11 21:19:49 GMT+08:00 1970

You can use time formatting method to change it to what you like. See my other blog for details. This function is not too Lots of flaws. The clear() function clears all variables in the object without parameters. The time after clearing is directly returned to its original shape and becomes

Thu Jan 01 00:00:00 GMT+ 08:00 1970

clear() can also be appended with the parameter int field, which means to clear this value only:

calendar.clear(Calendar.YEAR);System.out.println(calendar.getTime());

上述代码最后显示的年份是1970年(不可能清除成0000年…),其他的也可以以此类推。
isSet()方法确定日历字段是否已经设置了一个值,有些值会因为get方法触发计算而被设置,很多的时候,只要进行了初始化,很多值已经被设置了,但是作为一个boolean返回值的函数,检测的时候我们相信还是会起到作用的。

if(calendar.isSet(Calendar.DATE))

(六) 总结

Calendar类正如其名,可以实现一个日历,对其进行操作且功能较为完整。如果你只是需要一个时间,这个类并不一定比new Date()能快多少,但是对于一些细节的操作,还是有很多值得我们学习的地方。

 以上就是java时间----java.util.Calendar的详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download

Atom editor mac version download

The most popular open source editor