Java time class date, calendar and usage

Time:2022-1-14

Introduction to time class

In Java, time classes mainly includeDateCalendar, just for the time beingjava.util.*Time class under, forjava.sql.*The next one will not be introduced first.
The main contents are as follows.

  • 1. How to get the current time parameter
  • 2. How to pass the first and last days of a month
  • 3. How to add or subtract dates
  • 4. Gets the time difference between two times
First of all, we need to understand the introduction under the API. For date, many methods are outdated and migrated to the calendar class, but this is the initial time class. There are two main construction methods, namely
    Date date= new Date();// Assign objects and initial session
    Date date = new date (long date) // allocate a date object and initialize it to represent the specified number of milliseconds since the standard base time (called epoch), i.e. 00:00 GMT, January 1, 1970).
    It can be seen that date is based on the epoch. Simply verify your guess. new Date(). The value of getyear () is 120, but this year is 2020.
For calendar, the difference from date is that it offsets the time epoch of date. If you look at the one in parentheses, you can't look at it. API (calendar class) is an abstract class. It provides some methods for the conversion between a specific moment and a group of calendar fields such as year, month, day_of_month and hour, and provides some methods for operating calendar fields (such as obtaining the date of the next week). The moment can be expressed in milliseconds, which is the offset from the epoch (i.e. 00:00:00.000 Greenwich mean time on January 1, 1970, Gregorian calendar).
  What calendar has to say is the class method getInstance. The getInstance method of calendar returns a calendar object whose calendar field has been initialized by the current date and time

Calendar rightNow = Calendar.getInstance();

practice

  • 1. How to obtain current parameters
public void getCurrentTime() {
        Date NowDate = new Date();
        //The specific date format can be modified later. HH stands for 24-hour system and HH stands for 12-hour system,
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd a hh:mm:ss");
        String CurrentTime1 = formatter1.format(NowDate);
        String CurrentTime2 = formatter2.format(NowDate);
        System.out.println(CurrentTime1);
        System.out.println(CurrentTime2);
    }

Output results:

2020-09-02 08:45:25
2020-09-02 08:45:25 am
  • 2. How to get the first and last days of a month
//Get the last day of a month in a year
    //Note that the month is 12 months from 0 to 11, not from 1, but the day of the month starts from 1

    /**
     *Year corresponding to @ param year
     *@ param month corresponding month
     * @return
     */
    public static String getLastDayOfMonth(int year,int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month-1);
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DATE));

        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        String date = sdf.format(calendar.getTime());

        return date;
    }

    //Get the first day of a year and a month
    public static String getFirstDayOfMonth(int year,int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month-1);
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMinimum(Calendar.DATE));

        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        String date = sdf.format(calendar.getTime());

        return date;
    }

Test:

public void test() {
        String firstDayOfMonth = CalendarUtil.getFirstDayOfMonth(2020, 9);
        String lastDayOfMonth = CalendarUtil.getLastDayOfMonth(2020, 9);
        System.out.println(firstDayOfMonth+"---"+lastDayOfMonth);
    }

Output results

2020-09-01---2020-09-30
  • 3. How to add or subtract dates
The add method is provided in the calendar class
Add (F, delta) adds delta to the f field. There are two main rules

Add rule 1: the value of the f field after the call minus the value of the f field before the call is equal to Delta, based on any overflow in the field F. Overflow occurs when the field value is out of its range. As a result, the next larger field is incremented or decremented, and the field value is adjusted back into its range.

Add rule 2: if a smaller field is expected to remain unchanged, but it is impossible to make it equal to the previous value, because after the field F is changed, or after other constraints, such as the time zone offset, its maximum and minimum values are also changed, and then its value is adjusted to be as close as possible to the expected value. Smaller fields represent a smaller time unit. Hour is a better day than day_ OF_ Month small field. No adjustment is required for smaller fields that are not expected to be invariant fields. The calendar system determines which fields are expected to remain unchanged.

Code example:

//Date in the next n days
    public static String getTargetDay(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH,+day);
        Date time = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(time);

        return date;
    }

Test:

public void test5() {
        String targetDay1 = CalendarUtil.getTargetDay(20);
        String targetDay2 = CalendarUtil.getTargetDay(-20);
        System.out.println(targetDay1);
        System.out.println(targetDay2);
    }

result:

For example, it is now September 2. Pushing back 20 days is 22, and pushing forward 20 days is August 13

2020-09-22
2020-08-13
  • 4. Obtain the time difference between two times
There are many methods, which will not be repeated. It is mainly to convert time into time stamp, and finally calculate through the time stamp corresponding to the two times. Finally, convert the long timestamp to the format of the time you need

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Go: why atomic with sync?

Go is a language good at concurrency. Starting a new goroutine is as simple as typing “go”. As you find yourself building more and more complex systems, it becomes extremely important to properly protect access to shared resources to prevent competitive conditions. Such resources may include configurations that can be updated immediately (such as function […]