Calendar usage and Date usage in Java


1, Common class Calendar

Calendar programming example

2, Common class Date

Date programming instance

1, Common class Calendar

In earlier JDK versions, the Date class has two functions:

  1. Date can be interpreted in year, month, day, hour, minute and second.
  2. Allows formatting and parsing of strings representing dates.

JDK1.1 provides a class Calendar to complete the first function and a class DateFormat to complete the second function. DateFormat is   java.text   A class in the package. Unlike the Date class, the DateFormat class can accept Date strings expressed in various languages and habits.

However, the Calendar class is an abstract class, which completes the conversion between the Date class and the ordinary Date representation. We mostly use the GregorianCalendar class, a subclass of the Calendar class. It realizes the Gregorian Calendar system widely used in the world. Of course, we can also inherit the Calendar class, and then define and implement the Calendar method ourselves.

Let's take a look at the constructor of the GregorianCalendar class:

Construction methodexplain
GregorianCalendar()The relevant values in the created object are set to the specified time zone, and the current time of the default location, that is, the time zone in which the program runs and the current time of the location
GregorianCalendar(TimeZone zone)The relevant values in the created object are set to the specified time zone, the current time of the default location
GregorianCalendar(Locale aLocale)The relevant values in the created object are set to the default time zone, specifying the current time of the location a locale
GregorianCalendar(TimeZone zone,Locale aLocale)The relevant values in the created object are set to the specified time zone and the current time of the specified place

TimeZone is   java.util   Package that encapsulates information about time zones. Each time zone corresponds to a set of IDS. The TimeZone class provides methods to complete the conversion between the time zone and the corresponding ID.

For example:

//The Pacific time zone ID is PST
TimeZone tz0 = TimeZone.getTimeZone("PST")
//getDefault() can get the object of the time zone where the host is located
TimeZone tz1 = TimeZone.getDefault()

Locale is just a mechanism used to identify a specific geographical, political or cultural region and obtain the construction method of a locale object:

//Call the constructor of the Locale class
Locale l0 = new Locale(String language)
Locale l1 = new Locale(String language, String country)
Locale l2 = new Locale(String languge, String country, String variant)

//Call the constants defined in the Locale class
Locale  l1 = Locale.CHINA

Calendar programming example

New source code file

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class CalendarDemo {
    public static void main(String[] args) {
        System.out.println("Full display date and time:");
        // String conversion date format
        DateFormat fdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = fdate.format(new Date());

        // Create Calendar object
        Calendar calendar = Calendar.getInstance();
        // Initialize the Calendar object, but it is not necessary unless you need to reset the time
        calendar.setTime(new Date());

        // Show year
        System.out.println("Year: " + calendar.get(Calendar.YEAR));

        // Display month (starting from 0, the actual display needs to be increased by one)
        System.out.println("Month: " + calendar.get(Calendar.MONTH));

        // Current minutes
        System.out.println("minute: " + calendar.get(Calendar.MINUTE));

        // The nth day of this year
        System.out.println("This year's third " + calendar.get(Calendar.DAY_OF_YEAR) + "day");

        // The nth day of this month
        System.out.println("The third day of this month " + calendar.get(Calendar.DAY_OF_MONTH) + "day");

        // After 3 hours
        calendar.add(Calendar.HOUR_OF_DAY, 3);
        System.out.println("Time after three hours: " + calendar.getTime());
        // Format display
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());

        // Reset Calendar to display the current time
        calendar.setTime(new Date());
        str = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime());

        // Create a Calendar to compare time
        Calendar calendarNew = Calendar.getInstance();

        // Set to 5 hours ago, the latter is large and displays - 1
        calendarNew.add(Calendar.HOUR, -5);
        System.out.println("Time comparison:" + calendarNew.compareTo(calendar));

        // After setting for 7 hours, the former is large and displays 1
        calendarNew.add(Calendar.HOUR, +7);
        System.out.println("Time comparison:" + calendarNew.compareTo(calendar));

        // Return for 2 hours, the time is the same, and 0 is displayed
        calendarNew.add(Calendar.HOUR, -2);
        System.out.println("Time comparison:" + calendarNew.compareTo(calendar));

        // calendarNew creation time point
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendarNew.getTime()));
        // calendar creation time point
        System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS")).format(calendar.getTime()));
        System.out.println("Time comparison:" + calendarNew.compareTo(calendar));

Compile run:

Full display date and time:
2021-09-05 18:41:19
 Year: 2021
 Month: August
 Minutes: 41
 The 248 th day of this year
 The 5th day of this month
 Time after three hours: Sun Sep 05 21:41:19 CST 2021
2021-09-05 21:41:19:591
2021-09-05 18:41:19:593
 Time comparison:-1
 Time comparison:1
 Time comparison:0
2021-09-05 18:41:19:593
2021-09-05 18:41:19:593
 Time comparison: 0

After you run the above code, will you have any questions when you see the output results on the console?

actually   month   The meaning of is the same as that of the Date class. 0 represents January and 11 represents December.

Some students may not understand why the output of the last one is sometimes 0 and sometimes 1, which will be involved here   calendarNew   And   calendar   Create a new point in time, calendarnew   After increasing and reducing the time, it will be restored to the original time point, that is, the final comparison is who created it first, the later time point is larger, and   calendarNew   The time point created can only be greater than or equal to   calendar   , you need to compare according to the actual creation time point.

2, Common class Date

The Date class represents Date and time, which encapsulates the methods of operating Date and time. The Date class is often used to get the current time of the system.

Take a look at the non obsolete constructor defined in class Date:

Construction methodexplain
Date()Construct a Date object and initialize it to reflect the current time
Date(long date)Construct a Date object and initialize it according to the number of milliseconds relative to GMT January 1, 1970 00:00:00

Date programming instance

Create a new source code file

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {
    public static void main(String[] args) {
        String strDate, strTime;
        Date objDate = new Date();
        System.out.println("Today's date is:" + objDate);
        long time = objDate.getTime();
        System.out.println("Time in milliseconds since January 1, 1970( GMT): " + time);
        strDate = objDate.toString();
        //Extract GMT time
        strTime = strDate.substring(11, (strDate.length() - 4));
        //Extract time by hour, minute, and second
        strTime = "Time:" + strTime.substring(0, 8);
        //Format time
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Compile run:

Today's date is: Sun Sep 05 18:51:10 CST 2021
 Time in milliseconds since January 1, 1970( GMT): 1630839070659
 Time: 18:51:10
2021-09-05 18:51:10

Many methods of the Date class have been obsolete since JDK 1.1.

-------------------------------------------------------------There is no text below----------------------------------------------------

Tags: Java date

Posted on Sun, 05 Sep 2021 20:56:56 -0400 by Joan Collins