18 Java 8 date processing practices, very useful

Java 8 introduces a new date time API. In the tutorial, we will learn how to use the new API through some simple examples.

The way Java deals with date, calendar and time has always been criticized by the community. Setting java.util.Date as a variable type and the non thread safety of SimpleDateFormat make its application very limited.

The new API is based on ISO standard calendar system. All classes in java.time package are immutable and thread safe.

LocalDate in Java 8 is used to represent the date of the day. Unlike java.util.Date, it has only a date and no time. Use this class when you only need to represent dates.

 

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
System.out.println("today's date:" + today);
    }
}

LocalDate in Java 8 is used to represent the date of the day. Unlike java.util.Date, it has only a date, not a time. Use this class when you only need to represent dates.

Example 1: get today's date in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo01 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date:"+today);
    }
}

Example 2: getting year, month and day information in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo02 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        System.out.println("year:"+year);
        System.out.println("month:"+month);
        System.out.println("day:"+day);

    }
}

Example 3: processing specific dates in Java 8

We can easily create the date of the day through the static factory method now(). You can also call another useful factory method LocalDate.of() to create any date. This method needs to pass in the year, month and day as parameters and return the corresponding LocalDate instance. The advantage of this method is that it doesn't make old API design mistakes again, for example, the year starts from 1900, the month starts from 0, and so on.

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo03 {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2018,2,6);
        System.out.println("Custom date:"+date);
    }
}

Example 4: judge whether two dates are equal in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo04 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();

        LocalDate date2 = LocalDate.of(2018,2,5);

        if(date1.equals(date2)){
            System.out.println("Equal time");
        }else{
            System.out.println("Unequal time");
        }

    }
}

Example 5: checking for periodic events like birthdays in Java 8

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.MonthDay;

public class Demo05 {
    public static void main(String[] args) {
        LocalDate date1 = LocalDate.now();

        LocalDate date2 = LocalDate.of(2018,2,6);
        MonthDay birthday = MonthDay.of(date2.getMonth(),date2.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(date1);

        if(currentMonthDay.equals(birthday)){
            System.out.println("It's your birthday");
        }else{
            System.out.println("Your birthday hasn't arrived yet");
        }

    }
}

As long as the date of the day matches the birthday, the congratulations will be printed in any year. You can integrate the program into the system clock to see if it's reminded on your birthday, or write a unit test to see if the code is running correctly.

Example 6: get the current time in Java 8

package com.shxt.demo02;

import java.time.LocalTime;

public class Demo06 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        System.out.println("Get current time,Without date:"+time);

    }
}

You can see that the current time only contains time information, and there is no date

Example 7: get the current time in Java 8

It is common to calculate future time by adding hours, minutes, and seconds. In addition to the benefits of immutable type and thread safety, Java 8 also provides a better alternative to add() for the plusHours() method, which is compatible. Note that these methods return a brand-new instance of LocalTime. Because of its non variability, you must use variables to assign values after returning.

package com.shxt.demo02;

import java.time.LocalTime;

public class Demo07 {
    public static void main(String[] args) {
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(3);
        System.out.println("Three hours later:"+newTime);

    }
}

Example 8: how Java 8 calculates the date after a week

Similar to the previous example, which calculates the time after 3 hours, this example calculates the date after one week. The LocalDate date does not contain time information. Its plus() method is used to add days, weeks and months. The chrononunit class declares these time units. Since LocalDate is also an invariant type, it must be assigned with a variable after return.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Demo08 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's date is:"+today);
        LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
        System.out.println("One week later:"+nextWeek);

    }
}

You can see that the new date is seven days from the date of the day, that is, one week. You can add 1 month, 1 year, 1 hour, 1 minute or even a century in the same way. For more options, see the chrononunit class in the Java 8 API

Example 9:Java 8 calculates the date one year ago or one year later

Using minus() method to calculate the date one year ago

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Demo09 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date one year ago : " + previousYear);

        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date after one year:"+nextYear);

    }
}

Example 10: Clock class of Java 8

Java 8 adds a Clock class to get the time stamp at that time or the date and time information under the current time zone. Where System.currentTimeInMillis() and TimeZone.getDefault() were previously used, Clock can be used to replace them.

package com.shxt.demo02;

import java.time.Clock;

public class Demo10 {
    public static void main(String[] args) {
        // Returns the current time based on your system clock and set to UTC.
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock.millis());

        // Returns time based on system clock zone
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + defaultClock.millis());

    }
}

Example 11: how to use Java to determine whether a date is earlier than or later than another date

Another common operation in work is how to judge whether a given date is greater than or less than a day? In Java 8, the LocalDate class has two types of methods, isBefore() and isAfter(), for comparing dates. When calling the isBefore() method, returns true if the given date is less than the current date.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;


public class Demo11 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate tomorrow = LocalDate.of(2018,2,6);
        if(tomorrow.isAfter(today)){
            System.out.println("Date after:"+tomorrow);
        }

        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);
        if(yesterday.isBefore(today)){
            System.out.println("Previous date:"+yesterday);
        }
    }
}

Example 12: processing time zones in Java 8

Java 8 separates not only the date and time, but also the time zone. Now there are a series of separate classes such as ZoneId to handle specific time zones, and ZoneDateTime to represent the time in a time zone. This was done by the GregorianCalendar class before Java 8. The following example shows how to convert the time in this time zone to the time in another time zone.

package com.shxt.demo02;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Demo12 {
    public static void main(String[] args) {
        // Date and time with timezone in Java 8
        ZoneId america = ZoneId.of("America/New_York");
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
    }
}

Example 13: how to represent a fixed date such as the expiration of a credit card? The answer is year month

Similar to the example of MonthDay checking for duplicate events, YearMonth is another composite class that represents credit card maturity, FD maturity, futures option maturity, and so on. You can also use this class to get the total number of days in the current month. The lengthOfMonth() method of the YearMonth instance can return the number of days in the current month, which is very useful for judging whether there are 28 days or 29 days in February.

package com.shxt.demo02;

import java.time.*;

public class Demo13 {
    public static void main(String[] args) {
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());
        YearMonth creditCardExpiry = YearMonth.of(2019, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }
}

Example 14: how to check leap years in Java 8

package com.shxt.demo02;

import java.time.LocalDate;

public class Demo14 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        if(today.isLeapYear()){
            System.out.println("This year is Leap year");
        }else {
            System.out.println("2018 is not a Leap year");
        }

    }
}

Example 15: calculating days and months between two dates

A common date operation is to calculate the number of days, weeks, or months between two dates. In Java 8, you can use the java.time.Period class for calculation.

In the following example, we calculate the number of months between the current day and a future day.

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.Period;

public class Demo15 {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();

        LocalDate java8Release = LocalDate.of(2018, 12, 14);

        Period periodToNextJavaRelease = Period.between(today, java8Release);
        System.out.println("Months left between today and Java 8 release : "
                + periodToNextJavaRelease.getMonths() );


    }
}

Example 16: getting the current timestamp in Java 8

The Instant class has a static factory method now() that returns the current timestamp, as follows:

package com.shxt.demo02;

import java.time.Instant;

public class Demo16 {
    public static void main(String[] args) {
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp.toEpochMilli());
    }
}

The timestamp information contains both date and time, which is similar to java.util.Date. In fact, the Instant class is indeed the same as the date class before Java 8. You can use the date class and the Instant class's respective conversion methods to convert each other. For example, Date.from(Instant) will convert the Instant to java.util.Date, and Date.toInstant() will convert the date class to the Instant class.

Example 17: how to use predefined formatting tools to parse or format dates in Java 8

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Demo17 {
    public static void main(String[] args) {
        String dayAfterTommorrow = "20180205";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow,
                DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println(dayAfterTommorrow+"  The formatted date is:  "+formatted);
    }
}

Example 18: string to date type

package com.shxt.demo02;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Demo18 {
    public static void main(String[] args) {
        LocalDateTime date = LocalDateTime.now();

        DateTimeFormatter format1 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //Date to string
        String str = date.format(format1);

        System.out.println("Date to string:"+str);

        DateTimeFormatter format2 = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
        //String to date
        LocalDate date2 = LocalDate.parse(str,format2);
        System.out.println("Date type:"+date2);

    }
}
Published 5 original articles, won praise 5, and visited 3469
Private letter follow

Tags: Java less

Posted on Sun, 19 Jan 2020 09:07:25 -0500 by djjamiegee