API s related to time and date classes

1, Time API before JDK8

1.1 System static method

  the java.lang.System class provides public static long currentTimeMillis() to return the timestamp in milliseconds between the current time and 0:0:0 on January 1, 1970.

1.2 Date class

  • java.util.Date: represents a specific moment, accurate to milliseconds
    • constructor
      • public Date(): the object created with the null parameter constructor can obtain the current local time
      • public Date(long date): gets the number of milliseconds corresponding to the current Date object
    • common method
      • public long getTime(): returns the number of milliseconds represented by this Date object since January 1, 1970, 00:00:00 GMT
      • public String toString(): convert this Date object to the following String: dow mon dd hh:mm:ss zzz yyyy, where: dow is a day of the week (Sun,Mon,Tue,Wed,Thu,Fri,Sat), and zzz is the time standard
  • java.sql.Date: a variable corresponding to the date type in the database
  • How to convert java.sql.Date to java.util.Date: polymorphic
  • How to convert java.util.Date to java.sql.Date:
    • java.sql.Date date = new java.sql.Date(new java.util.Date.getTime())

1.3. SimpleDateFormat class

  • java.text.SimpleDateFormat: a class that formats and parses dates
    • format
      • public SimpleDateFormat(): creates objects in the default schema and locale
      • public SimpleDateFormat(String pattern): creates an object in the specified format
      • Public string fomat (date): format the time object date
    • analysis
      • public Date parse(String source): parses text from a given string to generate a date
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatTest{
    public static void main(String[] args) {
        //Format: date -- > string
        SimpleDateFormat sFormat = new SimpleDateFormat();
        Date date = new Date();
        String format = sFormat.format(date);
        System.out.println(format);             //8:01 pm on October 23, 2021

        //Parsing: String -- > date
        String string = "2021/10/23 8 p.m:01";
        try {
            Date date1 = sFormat.parse(string);
            System.out.println(date1);          //Sat Oct 23 20:01:00 CST 2021
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //format
        SimpleDateFormat sFormat1 = new SimpleDateFormat("yyyy-MM-dd hh:mm ss");
        String format1 = sFormat1.format(date);
        System.out.println(format1);             //2021-10-23 08:01 29

        //Parsing: the string must conform to the format recognized by SimpleDateFormat (reflected by constructor parameters), otherwise an exception will be thrown
        Date date1;
        try {
            date1 = sFormat1.parse("2021-10-23 08:01 29");
            System.out.println(date1);          //Sat Oct 23 08:01:29 CST 2021
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

1.4 Calendar

  • java.util.Calendar: abstract class, mainly used to complete the function of mutual operation between date fields
  • Method to get Calendar instance
    • Call Calendar.getInstance()
    • Call the constructor of GregorianCalendar of its subclass
  • An example of Calendar is the abstract representation of system time. get(int field) is used to obtain the desired time information
    • public void set(int field,int value)
    • public void add(int field,int amount)
    • public final Date getTime()
    • public final void setTime(Date date)
  • When getting the month: January is 0, February is 1, and so on, December is 11
  • Get week time: Sunday is 1, Monday is 2, and so on, Saturday is 7
import java.util.Calendar;
import java.util.Date;

public class CalendarTest {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);                                   //23
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));     //296

        calendar.set(Calendar.DAY_OF_MONTH, 21);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);                                   //21
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));     //294

        calendar.add(Calendar.DAY_OF_MONTH, 3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);                                   //24
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));     //297

        calendar.add(Calendar.DAY_OF_MONTH, -3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);                                   //21
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));     //294

        //getTime(): Calendar Class -- > date
        Date date = calendar.getTime();
        System.out.println(date);                                   //Thu Oct 21 21:21:44 CST 2021

        //setTime(): date -- > Calendar Class
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);                                   //23
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));     //296
    }
}

2, New date time API in JDK8

2.1,LocalDate,LocalTime,LocalDateTime

The instances of   LocalDate, LocalTime and LocalDateTime classes are immutable objects, which respectively represent the date and time using the ISO-8601 calendar system. They provide simple local date and time, and do not contain current time information or time zone related information;

  • LocalDate represents the date in IOS format (yyyy MM DD)
  • LocalTime represents a time, not a date
  • LocalDateTime is used to represent date and time

2.1.1 common methods

public static LocalDate now()                                       //Create objects according to the current family
public static LocalDate now(ZoneId zone)                            //Creates an object based on the specified time zone
public DayOfWeek getDayOfWeek()                                     //Get day of week
public static LocalDate of(int year, int month, int dayOfMonth)     //Creates an object based on the specified date
public static LocalTime of(int hour, int minute, int second)        //Creates an object at a specified time
public int getDayOfMonth()                                          //Obtain month days (1 ~ 31)
public int getDayOfYear()                                           //Days of acquisition year (1 ~ 366)
public int getSecond()                                              //Gets the second corresponding to the current object
public int getMinute()                                              //Gets the score corresponding to the current object
public int getHour()                                                //Gets the hour corresponding to the current object
public int getMonthValue()                                          //Obtain month (1 ~ 12)
public Month getMonth()                                             //Get month
public int getYear()                                                //Year of acquisition
public LocalDate withDayOfMonth(int dayOfMonth)                     //Modify the month and days to the specified value and return a new object
public LocalDate withDayOfYear(int dayOfYear)                       //Change the year and days to the specified value and return a new object
public LocalDate withMonth(int month)                               //Change the month to the specified value and return a new object
public LocalDate withYear(int year)                                 //Changes the year to the specified value and returns a new object
public LocalTime plusHours(long hours)                              //Adds a few hours to the current object
public LocalDate plusDays(long days)                                //Add a few days to the current object
public LocalDate plusWeeks(long weeks)                              //Adds a few weeks to the current object
public LocalDate plusMonths(long months)                            //Add a few months to the current object
public LocalDate plusYears(long years)                              //Add a few years to the current object
public LocalTime minusHours(long hours)                             //Subtracts a few hours from the current object
public LocalDate minusDays(long days)                               //Subtract a few days from the current object
public LocalDate minusWeeks(long weeks)                             //Subtracts a few weeks from the current object
public LocalDate minusMonths(long months)                           //Subtracts a few months from the current object
public LocalDate minusYears(long years)                             //Subtract a few years from the current object

2.2,Instant

   Instant represents an instantaneous point on the timeline. It provides the number of seconds from 0:00:0 (UTC) on January 1, 1970;

2.2.1 common methods

public static Instant now()                          //Returns the object of the Instant class of the default UTC time zone
public static Instant ofEpochMilli(long epochMilli)  //Returns the object of the Instant class based on 1970-01-01 00:00:00 plus the specified number of milliseconds
public OffsetDateTime atOffset(ZoneOffset offset)    //Create an OffsetDateTime with an immediate offset
public long toEpochMilli()                           //Returns the number of milliseconds from 1970-01-01 00:00:00 to the current time, which is the timestamp
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class InstantTest {
    public static void main(String[] args) {
        //now(): get the standard time corresponding to the original meridian
        Instant instant = Instant.now();   
        System.out.println(instant);        //2021-10-27T13:58:31.500988700Z
        
        //Add offset of time
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(9));
        System.out.println(offsetDateTime); //2021-10-27T22:58:31.500988700+09:00

        //Gets the number of milliseconds since 1970-01-01 00:00:00
        long milli = instant.toEpochMilli();
        System.out.println(milli);          //1635343111500

        //Ofepochmili(): obtain the Instant instance by the given number of milliseconds
        Instant instant2 = Instant.ofEpochMilli(1635343111500L);
        System.out.println(instant2);       //2021-10-27T13:58:18.519Z
    }
}

2.3,DateTimeFormatter

  • Predefined standard formats, such as ISO_LOCAL_DATE_TIMEļ¼› ISO_LOCAL_DATEISO_LOCAL_TIME
  • Localization related formats, such as oflocalized datetime (formatstyle. Long)
  • Custom formats, such as ofpattern ("yyyy MM DD HH: mm: SS e")

2.3.2 common methods

public static DateTimeFormatter ofPattern(String pattern)   //Returns a DateTimeFormatter in the specified string format
public String format(TemporalAccessor temporal)             //Format a date, time, and return string
public TemporalAccessor parse(CharSequence text)            //Parses the character sequence in the specified format into a date and time
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;

public class DateTimeFormatterTest {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        //Format: date -- > string
        LocalDateTime localDateTime = LocalDateTime.now();
        String string = formatter.format(localDateTime);
        System.out.println(localDateTime);  //2021-10-27T22:32:24.870061100
        System.out.println(string);         //2021-10-27T22:32:24.8700611

        //Parsing: String -- > date
        TemporalAccessor parse =  formatter.parse("2021-10-27T22:32:24.870061100");
        System.out.println(parse);          //{},ISO resolved to 2021-10-27T22:25:04.474825900

        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        //Format: date -- > string
        String string2 = formatter2.format(localDateTime);
        System.out.println(string2);        //October 27, 2021 10:32:24 PM
        //Format: date -- > string
        DateTimeFormatter formatter3 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String string3 = formatter3.format(LocalDate.now());
        System.out.println(string3);        //Wednesday, October 27, 2021

        //Custom format
        DateTimeFormatter formatter4 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //Format: date -- > string
        String string4 = formatter4.format(LocalDateTime.now());
        System.out.println(string4);        //2021-10-27 10:32:24

        //Parsing: String -- > date
        TemporalAccessor accessor =  formatter4.parse("2021-10-27 10:32:24");
        System.out.println(accessor);       //{MinuteOfHour=29, HourOfAmPm=10, MicroOfSecond=0, NanoOfSecond=0, SecondOfMinute=43, MilliOfSecond=0},ISO resolved to 2021-10-27
    }
}

2.4 other categories

  • Zoneld: this class contains all time zone information, including the ID of a time zone, such as Europe/Pairs
  • ZonedDateTime: a date and time in the time zone of the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Pairs
    • Each time zone corresponds to an ID, and the region ID is in the format of "{region} / {City}", such as Asia/Shanghai
  • Clock: a clock that uses the time zone to provide access to the current instant, date, and time
  • Duration, used to calculate two "time" intervals
  • Period, used to calculate the interval between two dates
  • TemporalAdjuster: time corrector
  • TemporalAdjusters: this class provides a large number of common TemporalAdjusters through static methods (firstDayOfXxx()/lastDayOfXxx()/nextXxx())

Tags: Java JavaSE

Posted on Sat, 30 Oct 2021 22:05:32 -0400 by ryankentp