Java Date class Date

catalogue

Constructor:

Common methods:

Format date using DateFormat

Format dates using SimpleDateFormat

Mutual conversion of date and date format string:

Calendar Class

Calendar and Date are tool classes that represent dates. They can be converted to each other.

Common methods provided by Calendar Class:

Constructor:

Date (int year, int month, int day) is out of date

Common Date (long date): the number of milliseconds of the specified time from standard time

Standard time: 1970-1-1-8:00

Common methods:

Mutual conversion of Date and millisecond in Date class:

1. Get the millisecond value of the date

Date date3 = new Date();

long time = date3.getTime();

2. Convert a millisecond value to Date

  1. Construction method
  2. setTime(long time) method

Format date using DateFormat

DateFormat is an abstract class that also provides several factory methods for obtaining DateFormat objects. All returned are subclass instances of the DateFormat object, which are instances of the same type.

  • getDateInstance(): returns a date formatter that formats only dates.
  • getTimeInstance(): returns a time formatter that formats only the time.
  • getDateTimeInstance(): returns a date and time formatter that formats both the time and the date.
  • getInstance(): returns a default system related date and time formatter.

give an example:

public static void main(String[] args)  throws Exception{

DateFormat format = DateFormat.getInstance();

System.out.println(format.getClass());

format = DateFormat.getDateInstance();

System.out.println(format.getClass());

format = DateFormat.getTimeInstance();

System.out.println(format.getClass());

}

Output:

 

Although all returned instances are of the same object type, according to different factory methods, the returned objects process different parts of information when formatting time objects.

Format dates using SimpleDateFormat

SimpleDateFormat is a subclass of DateFormat. It is a simpler date format that formats dates in the format we specify.

give an example:

 public static void main(String[] args) throws Exception{
            Date date = new Date();
            SimpleDateFormat simple = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
            System.out.println(simple.format(date));
        simple = new SimpleDateFormat("yyyy/MM/dd");
        System.out.println(simple.format(date));
    }

Output:

Mutual conversion of date and date format string:

String to date: parse()

Date to string: format()

public static void main(String[] args)  throws Exception{
		// Date -- String
		// Create date object
		Date d = new Date();
		// Given mode
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
		String s = sdf.format(d);
		System.out.println(s);
		
		//String -- Date
		String str = "2008-12-13 12:12:12"; 
		//When parsing a string into a date, please note that the format must match the given string format
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dd = sdf2.parse(str);
		System.out.println(dd);
	}

 

Note: yyyy, mm, dd, HH, mm and ss are strictly case sensitive. Otherwise, it will bring unpredictable problems.

The specific usage is as follows:

AlphabetMeaningExamples

y                

Year1996; 96. What year
M Month in year07. Which month of the year
m  Minute in hour    30. What minute of an hour
wWeek in year    27. The first few weeks of the year
WWeek in month2. The first few weeks of a month
DDay in year189 what day of the year
d Day in month10. The day of the month
HHour in day (0-23)

0 # the hour of the day (24-hour system)

hHour in am/pm (1-12)         

The 12th hour of the morning and the 12th hour of the afternoon

SMillisecond                 

978 milliseconds

sSecond in minute

55. The second of a minute

Calendar Class

Problems with Date class:

  1. Unable to achieve internationalization.
  2. Different attributes use inconsistent offsets. For example, the month and hour start from 0, the number of days in the month starts from 1, and the year starts from 1900.

Calendar is an abstract class that represents a calendar. Because the Date class has some defects in design, Java provides the calendar class to better handle Date and time.

The Calendar class cannot be created directly. You can create a subclass of Calendar through class methods. Java itself provides the GregorianCalendar subclass, which returns the default time zone and language environment through the getInstance() method to obtain a Calendar. The returned instance is the default subclass provided by Java

public static void main(String[] args)  throws Exception{
		Calendar cal = Calendar.getInstance();
		System.out.println(cal.getClass());  //class java.util.GregorianCalendar
	}

Calendar and Date are tool classes that represent dates. They can be converted to each other.

give an example:

public static void main(String[] args)  throws Exception{

Calendar cal = Calendar.getInstance();

Date date = cal.getTime();

System.out.println(date);

Calendar cale = Calendar.getInstance();

cale.setTime(date);

}

Common methods provided by Calendar Class:

  • void add(int field,int amount): adds or subtracts the specified amount of time for a given calendar field according to the rules of the calendar.
  • int get(int field): returns the value of the specified calendar field.
  • int getActualMaximum(int field): returns the maximum possible value of the specified calendar field.
  • int getActualMinimum(int field): returns the minimum possible value of the specified calendar field.
  • void roll(int field,int amout): similar to the add method, except that when the maximum range of the field is exceeded, it will not carry forward to the previous field.
  • void set(int field,int value): set the given calendar field to the given value.
  • void set(int year,int month,int date): sets the year, month, and day values of the Calendar object.
  • Void set (int year, int month, int date, int hourfday, int minute, int second): sets the values of the year, month, day, hour, minute and second fields of the Calendar object.
    public static void main(String[] args) throws Exception {
    		Calendar cal = Calendar.getInstance();
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		System.out.println("==================================");
    		System.out.println(sdf.format(cal.getTime()));
    		System.out.println(cal.get(Calendar.YEAR));
    		cal.add(Calendar.MONTH, 12);
    		System.out.println(cal.get(Calendar.YEAR));
    		System.out.println("=========================");
    		cal = Calendar.getInstance();
    		System.out.println(cal.get(Calendar.YEAR));
    		cal.roll(Calendar.MONTH, 12);
    		System.out.println(cal.get(Calendar.YEAR));
    		System.out.println("==================================");
    		System.out.println(cal.getActualMaximum(Calendar.MONTH)); // 11
    		System.out.println(cal.getActualMinimum(Calendar.MONTH)); // 0
    		System.out.println("==================================");
    		System.out.println(cal.get(Calendar.MONTH));
    		System.out.println(cal.get(Calendar.DAY_OF_MONTH));
    		System.out.println(cal.get(Calendar.DAY_OF_WEEK));
    		System.out.println(cal.get(Calendar.WEEK_OF_MONTH));
    		System.out.println(cal.get(Calendar.WEEK_OF_YEAR));
    
    		System.out.println("==================================");
    		cal.set(2018, 0, 1, 1, 1);
    		System.out.println(sdf.format(cal.getTime()));
    
    		/*
    		 * JANUARY = 0, FEBRUARY = 1, MARCH = 2, APRIL = 3, MAY = 4, JUNE = 5,
    		 * JULY = 6, AUGUST = 7, SEPTEMBER = 8, OCTOBER = 9, NOVEMBER = 10,
    		 * DECEMBER = 11, UNDECIMBER = 12
    		 */
    		System.out.println(cal.get(Calendar.MONTH));
    		/* Start with 1 */
    		System.out.println(cal.get(Calendar.DAY_OF_MONTH));
    		/*
    		 * SUNDAY = 1; Sunday MONDAY = 2; Monday TUESDAY = 3; WEDNESDAY = 4; THURSDAY
    		 * = 5; FRIDAY = 6; SATURDAY = 7; JANUARY = 0; Saturday
    		 */
    		System.out.println(cal.get(Calendar.DAY_OF_WEEK));
    		/* Start with 1 */
    		System.out.println(cal.get(Calendar.WEEK_OF_MONTH));
    		/* Start with 1 */
    		System.out.println(cal.get(Calendar.WEEK_OF_YEAR));
    	}

     

Keywords: Java Back-end

Added by prcollin on Wed, 23 Feb 2022 17:37:16 +0200