Lecture 27 Calendar time date class before JDK7

API

API stands for Application Programming Interface, and its full English name is Application Programming Interface.

API s are predefined functions intended to provide applications and developers the ability to access a set of routines based on a piece of software or hardware without having to access the source code or understand the details of the inner workings.

Date is one type of API.

Time class before JDK7

  • Data security issues may arise in a multi-threaded environment

standard Time

UTCChina Standard Timestandard reference time
Greenwich Mean Time: GMTUTC+8hJanuary 1, 1970 00:00:00 GMT
Atomic Clock: UTC

1 Date time class

The Date class represents a specific time with millisecond precision.

import package java.util.Date

1.1 Construction method

Construction methodillustrate
public Date()Create a Date object and initialize it to represent the current system time in milliseconds.
public Date(long date)Creates a Date object initialized to the specified number of milliseconds from the standard base time.

1.2 Common methods

member methodillustrate
public long getTime()Gets the millisecond value from the standard base time to a time object (for calculations, comparisons)
public void setTime(long time)Set the millisecond value of the time object, unit: millisecond value
import.java.util.Date;

public class Demo {
    public static void main(String[] args) {
        //Empty parameter construction
        Date d1 = new Date();
        System.out.println(d1);  // current time
        
        //Construct with parameters
		Date d2 = new Date(0L);
		System.out.println(d2);	// Thu Jan 01 08:00:00 CST 1970 // China is in East Eighth District, time difference
        
        //Use the set method to modify the millisecond value of the time object
        long time = 1000 * 60 * 60;
        d2.setTime(time);
        System.out.println(d2); // Thu Jan 01 09:00:00 CST 1970
        
        //Use the get method to get the millisecond value from January 1, 1970 00:00:00 to the time object
        long t = d2.getTime();
        System.out.println(t); // 3600000
    }
}

2 SimpleDateFormat parsing and formatting

SimpleDateFormat is a concrete class.

effect:

  • format(date->text);
  • parse(text->date);
  • Normalized date.

import package java.text.SimpleDateFormat

2.1 Construction method

Construction methodillustrate
public SimpleDateFormat()Format dates using default styles
public SimpleDateFormat(String pattern)format the date using the specified style

2.2 Common methods

member methodillustrate
public final String format(Date date)Formats the given date object as a string
public Date parse(String source)parses the given string into a date object

2.3 Formatting and parsing

Common pattern correspondences for formatted time forms

2020-07-23 9:13:23 -> yyyy-MM-dd HH:mm:ss

pattern lettercorrespond
yyear
Mmoon
dday
HTime
mMinute
sSecond
EDay of the week (day of the week)
aShow AM/PM

Formatted output date: from Date to String

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

public class SimpleDateFormatDemo1 {
    public static void main(String[] args) {
        //Construct with parameters
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM moon dd day HH:mm:ss");

        Date d = new Date(0L);
        
        // formatted output
        String s = sdf.format(d);
        System.out.println(s);// January 1, 1970 08:00:00
    }
}

Parsing Dates: From String to Date

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException; //abnormal

public class SimpleDateFormatDemo2 {
    public static void main(String[] args) throws ParseException {
		String s = "2059 May 12 10:44:20";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM moon dd day HH:mm:ss");
        
        // The format of the string to parse matches the format of the object
		Date d = sdf.parse(s);
        
        System.out.println(d); // Mon May 12 10:44:20 CST 2059
    }
}

application:

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

//Convert the string date 2000-11-11 to the string date November 11, 2000
public class SimpleDateFormatDemo2 {
    public static void main(String[] args) throws ParseException {
        //1. Analysis
        String date = "2000-11-11";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf1.parse(date);
        System.out.println(d);	// Sat Nov 11 00:00:00 CST 2000

        //2. Formatting
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy year MM moon dd day");
        String result = sdf2.format(d);
        System.out.println(result);	// November 11, 2000
    }
}

3 Calendar calendar class

Calendar is an abstract class and objects cannot be obtained directly.

effect:

  • Convert between a specific time and a calendar field;
  • Manipulate calendar fields (eg get next week's date).

import package java.util.Calendar

3.1 Get calendar object

public static Calendar getInstance() //Get the calendar object.

Method note:

  1. Underlying principle: The calendar object will be obtained according to the different time zones of the operating system, and the current time is represented by default.

  2. There is an array in the object, which is used to store the era, year, month, day, hour, minute, second, week and other information of the current time.

  3. In the array, the range of the month is 0~11, that is, if 1 is obtained, it means February.
    The beginning of the week is Sunday, that is, if 1 is obtained, it means Sunday.

  4. In the Calendar class, the information corresponding to the index in the array is encapsulated into a constant. get(Calendar.YEAR) indicates the year

3.2 Common methods

methodillustrate
public abstract void add(int field, int amount)According to the rules of the calendar, add/subtract the specified field amount
public int get(int field)Gets the value of the specified field (year, month, day, etc.) in the given calendar object
public final void set(int field, int value)Set the specified field in the current calendar to value
public final Date getTime()Get Date (date) object
public final setTime(Date date)Set a calendar object from a date object
public long getTimeInMillis()Get the time millisecond value of the calendar object
public void setTimeInMillis(long millis)Set time in milliseconds

3.3 Application

Use of get(int field)

get current date

import java.util.Calendar;

public class Demo {
    public static void main(String[] args) {
        // Create objects in polymorphic form
		Calendar c = Calendar.getInstance();

		// get date value 
		int year = c.get(Calendar.YEAR); 		//year
		int month = c.get(Calendar.MONTH) + 1;	//Months are counted from 0, so +1
		int date = c.get(Calendar.DATE); 		//day
        System.out.println(year + ", " + month + ", " + date);
    }
}

Use of add(int field, int amount)

Get five days ago ten years later

import java.util.Calendar;

public class Demo {
    public static void main(String[] args) {
		Calendar c = Calendar.getInstance();
        
		c.add(Calendar.YEAR, 10); 	 	//ten years later
		c.add(Calendar.DATE, -5);		//five days ago
        
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		int date = c.get(Calendar.DATE);
        System.out.println(year + ", " + month + ", " + date);
    }
}

Case: How many days are there in February of a year

import java.util.Calendar;
import java.util.Scanner;

public class CalendarTest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the year:");
        int year = sc.nextInt();
        // Set the calendar object to the input year, March, and 1st
        Calendar c = Calendar.getInstance();
        c.set(year, 2, 1);
        // March 1st is pushed forward by one day, which is the last day of February
        c.add(Calendar.DATE, -1);
        //get this day output
        int date = c.get(Calendar.DATE);
        System.out.println(year + "in february" + date + "sky");
    }
}

Tags: Java Algorithm Front-end

Posted by yonta on Sun, 08 Jan 2023 03:22:31 +0530