Ask Your Question
1

How can the given task be accomplished using SimpleDateFormat in Java?

asked 2021-12-14 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-06-11 18:00:00 +0000

djk gravatar image

To accomplish a given task using SimpleDateFormat in Java, follow these steps:

  1. Create a SimpleDateFormat object with the desired date/time format.

  2. Use the format method of SimpleDateFormat to convert a Date object or a string into a formatted date/time string.

For example, let's say we want to format the current date and time in the format "yyyy-MM-dd HH:mm:ss". The following code demonstrates how to use SimpleDateFormat to accomplish this task:

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

public class DateExample {
    public static void main(String[] args) {
        // Create a SimpleDateFormat object with the desired format
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // Get the current date and time
        Date now = new Date();

        // Format the current date and time using the SimpleDateFormat object
        String formattedDate = dateFormat.format(now);

        // Print the formatted date and time string
        System.out.println("Formatted Date: " + formattedDate);
    }
}

This will output the current date and time in the desired format: "Formatted Date: 2022-10-20 13:45:27".

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-12-14 11:00:00 +0000

Seen: 9 times

Last updated: Jun 11 '21