How to handle date and time in Java 8 or higher version?

How to handle date and time happily in Java 8 or higher java version?

How to use LocalDate to design a simple Calendar?

LocalDate provides some useful static methods to help develop some complexed programs. The simple calendar program as follwoing:

LocalDate date =;
        int month = date.getMonthValue();
        System.out.println("Month: " + month);
        int today = date.getDayOfMonth();
        System.out.println("Today: " + today);

        date = date.minusDays(today - 1);
        DayOfWeek weekday = date.getDayOfWeek();
        int value = weekday.getValue();

        System.out.println("Mon  Tue  Wed  Thu  Fri  Sat  Sun");
        for (int i = 1; i < value; i++) {
            System.out.print("     ");

        while (date.getMonthValue() == month) {
            System.out.printf("%3d", date.getDayOfMonth());
            if (date.getDayOfMonth() == today) {
                System.out.print("* ");
            } else {
                System.out.print("  ");
            date = date.plusDays(1);
            if (date.getDayOfWeek().getValue() == 1) {
        if (date.getDayOfWeek().getValue() != 1) {

Why Java 8 added LocalDate and LocalTime interface?

Java 8 has added a new interface LocalDateand LocalTimeinterface. Why do we need to develop a new set of APIs for processing dates and times? Because the old one java.util. Date is too difficult to use.

java.util.DateThe month 0starts, January is 0, December is 11, behave! java.time.LocalDate If the month and week are changed enum, it is impossible to use it wrong again.

java.util.DateAnd SimpleDateFormatterare not thread-safe, and LocalDateand LocalTimeand most basic String, it is the same type, not only thread-safe, and can not be modified.

java.util.DateIt is a “universal interface” that contains date, time, and milliseconds. If you only want to java.util. Date store the date, or only store the time, then only you know which parts of the data are useful and which parts of the data are not. use. In the new Java 8, the date and time are clearly divided LocalDate and LocalTime, LocalDateunable to contain the time, LocalTimecan does not contain date. Of course, LocalDateTimecan includes both date and time.

The reason why the new interface is easier to use is that it takes into account the operation of the date and time, and it often happens that it is pushed forward or backward for a few days. It takes a lot of code to use java.util.Date cooperation Calendar, and the average developer may not be able to write it right.

Leave a Reply

Your email address will not be published. Required fields are marked *