Home > Java > javaTutorial > How to Correctly Display the Current Date and Time in 'dd/MM/yyyy HH:mm:ss.SS' Format in Java?

How to Correctly Display the Current Date and Time in 'dd/MM/yyyy HH:mm:ss.SS' Format in Java?

Susan Sarandon
Release: 2024-12-20 08:55:10
Original
950 people have browsed it

How to Correctly Display the Current Date and Time in

How to Display Current Date and Time in "dd/MM/yyyy HH:mm:ss.SS" Format

In the provided Java code, the issue with displaying the date and time in the desired "dd/MM/yyyy HH:mm:ss.SS" format lies in the use of different SimpleDateFormat instances with different formatting patterns.

Solution:

To correctly format the date in both String and Date objects using the desired pattern, you should use the same SimpleDateFormat instance throughout the code, as follows:

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

public class DateAndTime {

    public static void main(String[] args) throws Exception {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");

        // Format the date as a String
        String strDate = sdf.format(cal.getTime());
        System.out.println("Current date in String Format: " + strDate);

        // Parse the formatted string back into a Date object
        Date date = sdf.parse(strDate);
        System.out.println("Current date in Date Format: " + sdf.format(date));
    }
}
Copy after login

By using the same SimpleDateFormat instance with the desired pattern, the output will be:

Current date in String Format: 05/01/2012 21:10:17.287
Current date in Date Format: 05/01/2012 21:10:17.287
Copy after login

This matches the specified "dd/MM/yyyy HH:mm:ss.SS" format for both String and Date representations.

The above is the detailed content of How to Correctly Display the Current Date and Time in 'dd/MM/yyyy HH:mm:ss.SS' Format in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template