Java Basic Tutorials - Date and Calendar classes

Keywords: PHP Java SQL

Both the Date and Calendar classes are classes about dates, both in the java.util package and require import when used.

Date

Objects of the java.util.Date class are used to represent time and date. The most frequently used object is to get the current date and time of the system, accurate to milliseconds.

There are two Date classes in Java, and one is java.sql.Date, which is generally not used and is not recommended even in databases.
When writing code, note that the imported package must be a java.util package.

import java.util.Date;
public class TestDate {
    public static void main(String[] args) {
        Date date = new Date(); // Get the current system date and time
        System.out.println("Today's date is:" + date);
        Date dateL = new Date(0L);// Parametric Version: Parameters are in milliseconds
        System.out.println("Date(long date)The date is:" + dateL);
        long time = date.getTime(); // Get milliseconds
        System.out.println("Time in milliseconds since January 1, 1970(GMT):" + time);
        // Deprecated, not in favor of use. It is recommended to use Calendar instead.
        Date dateYMD = new Date(1999, 01, 02);
        Date dateYMDHMS = new Date(1999, 01, 02, 10, 10, 10);
    }
}

DateFormatter
simpleDateFormat.format(_date): Converts the Date type to a formatted string
SimeDateFormat. parse ("1949-10-01"): Converts a formatted string to a Date type

import java.text.DateFormat;// abstract class
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
// DateFormat: Date_Text
public class TestDate Format {
    public static void main(String[] args) {
        Date _date = new Date(); // Get the current system date and time
        // Create a DateFormat object
        DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // format(Date date): Converts the date to a string in the specified mode
        String _s = _dateFormat.format(_date);
        System.out.println("SimpleDateFormat:" + _s);
        // -------------------------------
        // parse method: parsed in the specified format
        try {
            Date parse = _dateFormat.parse("1949-10-01");
            System.out.println(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
} 

Many methods in the Date class are declared "obsolete", which is not unavailable but disapproved of.
For example, Date's construction method with years, months and days in the first paragraph of the code above.

    @Deprecated
    public Date(int year, int month, int date) {
        this(year, month, date, 0, 0, 0);
    }

The Calendar class is recommended if you want to construct an object of date type by year, month and day.

Calendar

The java.util.Calendar class (calendar) is an abstract class and cannot be instantiated.

public abstract class Calendar implements Serializable, Cloneable, Comparable<Calendar> {
    ......
}

To get objects, you can only get them by calling the getInstance method java Calendar cal = Calendar.getInstance();

Generally, you get an instance object of Gregorian Calendar, which you can see from the output of toString().

Method explain
Calendar getInstance() Get the Calendar object
Date getTime() Calendar object to Date object
int get(int fields) Gets the value of the specified part of fields
void set(int fields, int value) Set the value specified in value to the part specified by fields
void add(int fields, int amount) Add amount value to the time or date part specified by fields
Object clone() Returns a copy of the calling object
void clear() Clear all time components of the current object
boolean after(Object obj) If the object time is called after obj, return true
boolean before(Object obj) If the object time is called before obj, return true
boolean equals(Object obj) Determine whether the calling object is equal to obj
import java.util.Calendar;
public class TestCalendar {
    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        // int _year = 2019, _month = 1, _day = 1;
        // cal.set(_year, _month - 1, _day);
        System.out.println(cal.get(Calendar.YEAR) + ":year");
        System.out.println(cal.get(Calendar.MONTH) + ":Month, starting from 0");
        System.out.println(cal.get(Calendar.DATE) + ":Day 1-31");
        System.out.println(cal.get(Calendar.DAY_OF_MONTH) + ":Day 1-31");
        System.out.println(cal.get(Calendar.DAY_OF_WEEK) + ":Week, Sunday, Day 1");
        System.out.println(cal.get(Calendar.WEEK_OF_MONTH) + ":Month n week");
        System.out.println(cal.get(Calendar.WEEK_OF_YEAR) + ":Year 1 n week");
        System.out.println(cal.get(Calendar.DAY_OF_YEAR) + ":First in a year n day");
        System.out.println(cal.get(Calendar.HOUR) + ":12 Hourly system");
        System.out.println(cal.get(Calendar.HOUR_OF_DAY) + ":24 Hourly system");
        System.out.println(cal.get(Calendar.MINUTE) + ":branch");
        System.out.println(cal.get(Calendar.SECOND) + ":second");
        System.out.println(cal.get(Calendar.MILLISECOND) + ":Millisecond");
        // A year after February 29, leap year
        cal.set(2000, 2 - 1, 29);
        // Change calendar to date
        System.out.println(cal.getTime());
        cal.add(Calendar.YEAR, 1);
        System.out.println(cal.getTime());
    }
}

* new time package for Java 8

java.time for date and time processing
| --Clock class: Gets the date and time of the specified time zone
| - Duration class: a period of time
| Instant class: specific time, accurate to nanoseconds
| LocalDate class: Time without time zone
......

import java.time.*;
public class TestDateJava8 {
    public static void main(String[] args) {
        testClock();
        testDuration();
        testInstant();
        testLocalDate();
    }
    static void testClock() {
        System.out.println("---Clock Class: Gets the date and time of the specified time zone---");
        Clock clock = Clock.systemUTC();// World Unified Time
        System.out.println("The current moment is:" + clock.instant());
        // millis() gets the number of milliseconds corresponding to the clock, the same as the System.currentTimeMillis() output
        System.out.println(clock.millis() + ":clock.millis()");
        System.out.println(System.currentTimeMillis() + ":System.currentTimeMillis()");
    }
    static void testDuration() {
        System.out.println("---Duration Category: A period of time---");
        int s = 60 * 59;// 60 seconds * 59 = 59 minutes
        Duration d = Duration.ofSeconds(s);
        System.out.println(s + "Second equals" + d.toMinutes() + "branch");
        System.out.println(s + "Second equals" + d.toHours() + "hour");
        System.out.println(s + "Second equals" + d.toDays() + "day");
    }
    static void testInstant() {
        System.out.println("---Instant Class: Specific time, accurate to nanoseconds---");
        Instant instant = Instant.now();// Get the current time
        System.out.println(instant + ": Instant.now() ");
        Instant instant2 = instant.plusSeconds(6000);
        System.out.println(instant2 + ": It requires extra times plusSeconds()");
    }
    static void testLocalDate() {
        System.out.println("---LocalDate Class: Time without time zone---");
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate + ": LocalDate.now()");
        // On the day of a year
        int _One year = 2017, _Days = 100;
        localDate = LocalDate.ofYearDay(_One year, _Days);
        System.out.println(localDate + ": " + _One year + "year,The first" + _Days + "day LocalDate.ofYearDay()");
    }
}

Posted by stilgar on Fri, 12 Jul 2019 12:14:29 -0700