"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 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?

2025-03-25에 게시되었습니다
검색:894

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));
    }
}

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.

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3