Parse and Format Date Time in Java 8

by Didin J. on Dec 22, 2016 Parse and Format Date Time in Java 8

How to parse and format date time in Java 8 that most used everywhere in Java programming language.

The most popular use of java programming language is date-time conversion. Every string data that has date format need to parse into right java date, also every java date needs to formatted to the required date format that displayed on the screen. Java DateTime format required when you need to display a date, time, or DateTime in a different form.

 

Parsing String to Java Date Time

For example, you have a string that shows a date like this "Dec 12, 2016" and you have to convert to right java datetime format. You can do as this code below.

package parsedatetimeexample;

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

public class ParseDateTimeExample {

    public static void main(String[] args) {
        String today = "Dec 12, 2016";
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy");
            LocalDate date = LocalDate.parse(today, formatter);
            System.out.printf("%s%n", date);
        } catch (DateTimeParseException exc) {
            System.out.printf("%s is not parsable!%n", today);
            throw exc;
        }
    }

}

If you compile and run this code, it's will display right Java Date in the console.

run:
2016-12-12
BUILD SUCCESSFUL (total time: 0 seconds)

 

Formatting Java Date Time

If you want to display a date in the format that you wanted, you can follow this example below that implements Java DateTime format.

package formatdatetimeexample;

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

public class FormatDateTimeExample {

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

        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy HH:mm:ss");
            String dateText = date.format(formatter);
            System.out.println(dateText);
        } catch (DateTimeException exc) {
            System.out.printf("%s can't be formatted!%n", date);
            throw exc;
        }

    }

}

 

It will result in the formatted date.

run:
Dec 22, 2016 20:48:10
BUILD SUCCESSFUL (total time: 1 second)

That so easy right?

Thanks

Loading…