Table of Contents
java.util.Calendar
(1) Instantiation
(2) Class variables
(3) compareTo() after() before() function
(4) get() add() set() setTime() function
(5) getTime() clear() isSet() function
(六) 总结
Home Java javaTutorial java time----detailed introduction to java.util.Calendar

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

Mar 01, 2017 pm 01:22 PM

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);
Copy after login

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();
Copy after login


(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);
Copy after login

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);
Copy after login

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));
Copy after login

(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());
Copy after login

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
Copy after login


(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());
//输出的日期是当前日期的前一天,其他所有的都不变
Copy after login

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对象
Copy after login

(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());
Copy after login

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

if(calendar.isSet(Calendar.DATE))
Copy after login

(六) 总结

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

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


Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1652
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles