Date Time Formatting and Date Manipulations


Date Time Formatting

Before Java 8, there was DateFormat and SimpleDateFormat classes in the package java.text and this legacy code will be continued to be used for sometime

But, Java 8 offers a modern approach to handling Formatting and Parsing.

In formatting and parsing first you pass a String object to DateTimeFormatter, and in turn use it for formatting or parsing.

import java.time.*;
import java.time.format.*;
 
class DifferentDateTimeFormat {
    public static void main(String[] args) {
        // Parsing
        String pattern = "MM-dd-yyyy HH:mm";
        DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern(pattern);
 
        LocalDateTime defaultDateTime = LocalDateTime.parse("2019-07-15T09:30"); // Default format
        LocalDateTime customFormattedDateTime = LocalDateTime.parse("07-25-2023 14:45", customFormatter);
 
        System.out.println(defaultDateTime + "\n" + customFormattedDateTime); // Will be printed in default format
 
        // Formatting
        DateTimeFormatter customFormat = DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy HH:mm");
 
        DateTimeFormatter isoFormat = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        LocalDateTime now = LocalDateTime.now();
 
        System.out.println(now.format(customFormat) + "\n" + now.format(isoFormat));
    }
}

An important notice, instead of using Custom patterns, it is good practice to use predefined formatters. Your code look more clear and usage of ISO8061 will definitely help you in the long run.


Simple Date Manipulations

Get the current date.

LocalDate.now()

Get yesterday's date.

LocalDate y = LocalDate.now().minusDays(1);

Get tomorrow's date

LocalDate t = LocalDate.now().plusDays(1);

Get a specific date.

LocalDate t = LocalDate.of(1974, 6, 2, 8, 30, 0, 0);

In addition to the plus and minus methods, there are a set of "with" methods that can be used to set a particular field on a LocalDate instance.

LocalDate.now().withMonth(6);

The example above returns a new instance with the month set to June (this differs from java.util.Date where setMonth was indexed a 0 making June 5).

Because LocalDate manipulations return immutable LocalDate instances, these methods may also be chained together.

LocalDate ld = LocalDate.now().plusDays(1).plusYears(1);

This would give us tomorrow's date one year from now.

Basic Programs