Java Time Formatting: SimpleDateFormat Guide

In Java, you can use the SimpleDateFormat class to format time. Here is an example code:

import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeFormatting {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String formattedDate = sdf.format(date);
        System.out.println("Formatted Date: " + formattedDate);
    }
}

In this example, we created a SimpleDateFormat object and specified the format of the date and time as “yyyy-MM-dd HH:mm:ss”. Then, we called the format() method to format the Date object into a string with the specified format. Finally, we printed out the formatted time string.

When running this code, the output will be as follows:

Formatted Date: 2021-08-26 15:30:45
bannerAds