The CTO strongly prohibits the use of Calendar, so what?

background

Java 8 has been widely used, but some people still use Java Calendar to process time and date. Not only is the performance poor, but the code is very redundant. Can't they use the new API provided by Java 8?

So the CTO is mandatory, must use Java 8 to deal with the date, otherwise all will be fired. Below are 18 ways to deal with dates that can be collected and must be useful.

The way Java handles dates, calendars, and times has long been criticized by the community, making java.util.Date a mutable type, and the non-thread-safety of SimpleDateFormat making its application very limited.

The new API is based on the ISO standard calendar system, and all classes under the java.time package are immutable and thread-safe.

18 Java8 Date Handling Practices

| Example 1: Get today's date in Java 8

LocalDate in Java 8 is used to represent today's date. Unlike java.util.Date, it only has the date, not the 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);
    }
}
/*
 operation result:

  Today's date: 2018-02-05
*/

| Example 2: Get year, month, 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: Handling specific dates in Java 8

We can easily create today's date through the static factory method now(). You can also call another useful factory method, LocalDate Of () creates 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 the design mistakes of the old API are not repeated, such as the year starts at 1900, the month starts at 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: Determine if 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("time equal");
        }else{
            System.out.println("time varies");
        }

    }
}

| Example 5: Checking for recurring 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("is your birthday");
        }else{
            System.out.println("your birthday hasn't come yet");
        }

    }
}

A congratulatory message will be printed regardless of the year as long as today's date and birthday match. You can integrate your program into the system clock to see if you are reminded of your birthday, or write a unit test to check that the code is working correctly.

| Example 6: Get 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,no date:"+time);

    }
}

You can see that the current time only contains time information, no date.

| Example 7: Get current time in Java 8

It is common to calculate future times by adding hours, minutes, and seconds. In addition to the benefits of immutable types and thread safety, Java 8 provides a better plusHours() method to replace add() and is compatible.

Note that these methods return a brand new LocalTime instance, and because of its immutability, you must assign values ​​to variables 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("After three hours the time is:"+newTime);

    }
}

| Example 8: How Java 8 calculates the date one week later

Similar to the previous example calculating the time 3 hours later, this example will calculate the date one week later.

A LocalDate date does not contain time information, its plus() method is used to add days, weeks, and months, and the ChronoUnit class declares these time units. Since LocalDate is also an invariant type, it must be assigned a variable after returning.

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("A week later the date is:"+nextWeek);

    }
}

You can see that the new date is 7 days away from the current date, which 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 check out the ChronoUnit class in the Java 8 API.

| Example 9: Java 8 calculate date one year ago or one year later

Calculate the date a year ago using the minus() method:

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("a year ago date : " + previousYear);

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

    }
}

| Example 10: Java 8's Clock class

Java 8 adds a Clock class to get the current timestamp, or date and time information in the current time zone.

The previous use of System.currentTimeInMillis() and TimeZone.getDefault() can be replaced with Clock.

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 tell if a date is before or after another date in Java
Another common operation in work is how to judge whether a given date is greater than or less than a certain day?

In Java 8, the LocalDate class has two methods isBefore() and isAfter() for comparing dates. Returns true if the given date is less than the current date when the isBefore() method is called.

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("after date:"+tomorrow);
        }

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

| Example 12: Handling time zones in Java 8

Java 8 not only separates date and time, but also time zone. There are now a series of separate classes such as ZoneId to deal with a specific time zone, and the ZoneDateTime class to represent the time in a certain time zone.

This was done by the GregorianCalendar class until 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 a credit card expiration, the answer is in YearMonth

Similar to the MonthDay example of checking for duplicate events, YearMonth is another composite class used to represent credit card expiration, FD expiration, futures option expiration, etc.

You can also use this class to get the 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 when judging whether February has 28 days or 29 days.

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 for leap year 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: Calculate the number of 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 to do calculations.

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: Get 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());
    }
}

Timestamp information contains both date and time, much like java.util.Date.

In fact, the Instant class is indeed equivalent to the Date class before Java 8. You can use the respective conversion methods of the Date and Instant classes to convert each other.

For example: Date.from(Instant) converts Instant to java.util.Date, Date.toInstant() converts Date class to Instant class.

| Example 17: How to parse or format dates using predefined formatters 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 Interchange 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("convert 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);

    }
}

Source: juejin.cn/post/6937888716438372389

Tags: Java servlet jvm

Posted by chandan_tiwari on Thu, 22 Sep 2022 22:02:00 +0530