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.
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!