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)); } }
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
This matches the specified "dd/MM/yyyy HH:mm:ss.SS" format for both String and Date representations.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3