web123456

Detailed explanation of date and time classes in Java (Date, DateFormat, Calendar)

Table of contents

    • 1 Date class
      • 1.1 Overview
      • 1.2 Date class construction method
      • 1.3 GetTime method of Date class: return the number of milliseconds
    • 2 DateFormat class
      • 2.1 The constructor method of its subclass SimpleDateFormat
      • 2.2 Common methods of DateFormat class
        • 2.2.1 format method
        • 2.2.2 parse method
      • 2.3 Comprehensive exercises
    • 3 Calendar class
      • 3.1 Concept
      • 3.2 Obtaining method
      • 3.3 Common methods
        • 3.3.1 get/set method
        • 3.3.2 add method
        • 3.3.3 getTime method: Return the corresponding Date object

1 Date class

1.1 Overview

Classes represent specific moments, precise to milliseconds. The constructor of the Date class can be used toConvert millisecond value to date object

1.2 Date class construction method

  • public Date(): Assign the Date object and initialize this object to indicate the time it was allocated (accurate to milliseconds).
  • public Date(long date): Assign the Date object and initialize this object to represent the specified number of milliseconds since the standard benchmark time (called "epoch", i.e. 00:00:00 GMT on January 1, 1970).

tips: Since we are in the East Eighth District, our base time is 8:00:00 on January 1, 1970.

Simply put: using the parameterless construction, the millisecond time of the current system time can be automatically set; specify the long type of construction parameters, and the millisecond time can be customized. For example:

import java.util.Date;

public class DemoDate {
    public static void main(String[] args) {
        // Create a date object and convert the current time into a date object
        System.out.println(new Date()); // Sat Sep 19 23:11:21 CST 2020
        // Create a date object and convert the current millisecond value into a date object
        System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970
    }
}

tips: When using the println method, the toString method in the Date class will be automatically called. The Date class overrides and overrides the toString method in the Object class, so the result is a string of the specified format.

1.3 GetTime method of Date class: return the number of milliseconds

2 DateFormat class

It is an abstract class of the date/time formatting subclass. Through this class, we can help us complete the conversion between date and text, that is, we can convert back and forth between the Date object and the String object.

  • format: Convert from a Date object to a String object in the specified format. (format)
  • Analysis: Convert from a String object to a Date object in the specified format. (parse)

2.1 The constructor method of its subclass SimpleDateFormat

Since DateFormat is an abstract class and cannot be used directly, it requires commonly used subclasses. This class requires a schema (format) to specify the standard for formatting or parsing. The construction method is:

  • public SimpleDateFormat(String pattern): Construct SimpleDateFormat with the given schema and date format symbols of the default locale.

The parameter pattern is a string representing a custom format for date and time.

Format rules

Common format rules are:

Identification letters (case sensitive) meaning
y Year
M moon
d day
H hour
m point
s Second

The code for creating a SimpleDateFormat object is like:

import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class Demo02SimpleDateFormat {
    public static void main(String[] args) {
        // The corresponding date format is as follows: 2018-01-16 15:06:38
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    }    
}

2.2 Common methods of DateFormat class

Common methods of the DateFormat class are:

  • public String format(Date date): Format the Date object into a string.
  • public Date parse(String source): Parses the string into a Date object.
2.2.1 format method

The code using the format method is:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
  Convert Date object to String
 */
public class Demo03DateFormatMethod {
    public static void main(String[] args) {
        Date date = new Date();
        // Create a date format object, you can specify the style when obtaining the formatted object
        DateFormat df = new SimpleDateFormat("Yyyyy MM month dd day");
        String str = df.format(date);
        System.out.println(str); // September 19, 2020
    }
}
2.2.2 parse method

The code using the parse method is:

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
  Convert String to Date object
 */
public class Demo04DateFormatMethod {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("Yyyyy MM month dd day");
        String str = "December 11, 2018";
        Date date = df.parse(str);
        System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
    }
}

2.3 Comprehensive exercises

topic: Please use the date and time-related API to calculate how many days a person has been born.

Ideas:

1. Get the millisecond value corresponding to the current time

2. Get the millisecond value corresponding to your date of birth

3. Two times subtract (current time – date of birth)

Code implementation:

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

/*
  Convert String to Date object
 */
public class Demo {
    public static void main(String[] args) throws ParseException {
        System.out.println("Please enter the date of birth format YYYY-MM-dd");
        // Get the date of birth, keyboard input
        String birthdayString = new Scanner(System.in).next();
        // Convert the string date into a Date object
        // Create SimpleDateFormat object, write date mode
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // Call method parse, convert the string into a date object
        Date birthdayDate = sdf.parse(birthdayString);
        // Get today's date object
        Date todayDate = new Date();
        // Convert two dates to millisecond values, the method of Date class getTime
        long birthdaySecond = birthdayDate.getTime();
        long todaySecond = todayDate.getTime();
        long secone = todaySecond-birthdaySecond;
        if (secone < 0){
            System.out.println("None have been born yet");
        } else {
            System.out.println(secone/1000/60/60/24);
        }
    }
}
Please enter the date of birth format YYYYY-MM-dd
2019-09-12
373

3 Calendar class

3.1 Concept

It is a calendar class, which appears after Date, replacing many Date methods. This class encapsulates all possible time information into static member variables for easy access. The calendar class is convenient for obtaining various time attributes.

3.2 Obtaining method

Calendar is an abstract class. Due to language sensitivity, the Calendar class is not created directly when creating an object, but is created through static methods and returns a subclass object, as follows:

Calendar static method

  • public static Calendar getInstance(): Get a calendar using the default time zone and locale

For example:

import java.util.Calendar;

public class Demo06CalendarInit {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
    }    
}

3.3 Common methods

According to the API documentation of the Calendar class, common methods are:

  • public int get(int field): Returns the value of the given calendar field.
  • public void set(int field, int value): Set the given calendar field to the given value.
  • public abstract void add(int field, int amount): Add or subtract the specified amount of time for a given calendar field according to the rules of the calendar.
  • public Date getTime(): Returns a Date object representing this Calendar time value (millisecond offset from epoch to present).

There are many member constants in the Calendar class representing the given calendar field:

Field value meaning
YEAR Year
MONTH Month (start from 0, can be used +1)
DAY_OF_MONTH Day in the middle of the moon (when)
HOUR Time (12-hour system)
HOUR_OF_DAY Time (24-hour system)
MINUTE point
SECOND Second
DAY_OF_WEEK Mid-week day (day of the week, Sunday is 1, can be used -1)
3.3.1 get/set method

The get method is used to get the value of the specified field, and the set method is used to set the value of the specified field. The code uses a demonstration:

import java.util.Calendar;
public class Demo {
    public static void main(String[] args) {
        // Create Calendar object
        Calendar cal = Calendar.getInstance();
        // Get the year
        int year = cal.get(Calendar.YEAR);
        // Get Month
        int month = cal.get(Calendar.MONTH) + 1;
        // Getting Day
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "Year" + month + "moon" + dayOfMonth + "day");
    }
}
2020Year9moon20day
import java.util.Calendar;

public class Demo07CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // Set the year
        cal.set(Calendar.YEAR, 2018);
        // Get the year
        int year = cal.get(Calendar.YEAR);
        // Get Month
        int month = cal.get(Calendar.MONTH) + 1;
        // Getting Day
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.print(year + "Year" + month + "moon" + dayOfMonth + "day");
    }
}
2018Year9moon20day
3.3.2 add method

The add method can add or subtract the value of the specified calendar field. If the second parameter is a positive number, the offset is added, and if it is a negative number, the offset is subtracted. Codes like:

import java.util.Calendar;

public class Demo08CalendarMethod {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // Get the year
        int year = cal.get(Calendar.YEAR);
        // Get Month
        int month = cal.get(Calendar.MONTH) + 1;
        // Getting Day
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year + "Year" + month + "moon" + dayOfMonth + "day");
        // Use the add method
        cal.add(Calendar.DAY_OF_MONTH, 2); // Add 2 days
        cal.add(Calendar.YEAR, -3); // 3 years off
        // Get the year
        year = cal.get(Calendar.YEAR);
        // Get Month
        month = cal.get(Calendar.MONTH) + 1;
        // Getting Day
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println(year + "Year" + month + "moon" + dayOfMonth + "day");
    }
}
2020Year9moon20day2017Year9moon22day
3.3.3 getTime method: Return the corresponding Date object

The getTime method in Calendar does not get the millisecond moment, but gets the corresponding Date object.

import java.util.Calendar;
import java.util.Date;

public class Demo {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        System.out.println(date); 
    }
}
Sun Sep 20 08:44:18 CST 2020

Tips:

​ The start of Western Week is Sunday (1) and Monday (2), and China is Monday, so it can be used -1.

​ In the Calendar class, the month's representation is 0-11 for January-December (can be used +1).

​ The date has a size relationship. If the time is late, the greater the time.