DEV Community

Edem Agbenyo
Edem Agbenyo

Posted on • Updated on

100 Days of Java: Day 2

Welcome to Day 2 of the 100 Days of Code challenge! Today, we'll be diving into a Java code snippet that deals with date and time manipulation. Let's break down the code and understand what each part does.

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

public final class MyDateFormatter {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

    public static void main(String[] args) {
        LocalDateTime currentDateTime = LocalDateTime.now();
        String formattedDateTime = currentDateTime.format(FORMATTER);
        System.out.println(formattedDateTime);
    }

}

Enter fullscreen mode Exit fullscreen mode

To begin, we import two classes from the java.time package: LocalDateTime and DateTimeFormatter. These classes provide functionalities to handle dates, times, and their formatting.

Next, we define a class called MyDateFormatter. The final keyword means that this class cannot be extended, ensuring that it remains as is. This class will contain our code for today.

Within the class, we declare a constant variable called FORMATTER of type DateTimeFormatter. This formatter object is used to specify the desired format for the date and time.

Moving on to the main method, we create a LocalDateTime object named currentDateTime using the now() method. This object represents the current date and time.

We then format this currentDateTime using the FORMATTER object, and store the formatted date and time as a string in the variable formattedDateTime.

Finally, we use System.out.println() to print the formattedDateTime string to the console.

Now that we understand the code, let's summarize what it does. When we run this program, it will display the current date and time in the format specified by the FORMATTER. In this case, the format is "dd/MM/yyyy HH:mm:ss", which means the date will be displayed as day/month/year, followed by the time in hours:minutes:seconds.

This simple code snippet demonstrates how to work with dates and times in Java using the java.time package. Feel free to experiment with different formats or explore more functionalities provided by this package.

That's it for Day 2! Stay tuned for the next code snippet and explanation tomorrow. Happy coding!

Code credits: https://github.com/hbelmiro/

Top comments (0)