Lang/Java

밀리세컨드 범위 동적으로 사용

hamaganatanadda 2023. 5. 7. 16:46

1.8 기준

공식 문서 참고

 

appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)

field - the field to append, not null

minWidth - the minimum width of the field excluding the decimal point, from 0 to 9

maxWidth - the maximum width of the field excluding the decimal point, from 1 to 9

decimalPoint - whether to output the localized decimal point symbol

 

Thread 환경(toFormatter() 써야 안전한듯..)

This class is a mutable builder intended for use from a single thread.

public static final DateTimeFormatter formatter1 = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd HH:mm:ss")
            .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
            .toFormatter();

public static final DateTimeFormatter formatter2 = new DateTimeFormatterBuilder()
            .appendPattern("yyyy-MM-dd HH:mm:ss")
            .appendFraction(ChronoField.MICRO_OF_SECOND, 0, 9, true)
            .toFormatter();

String date = "2023-01-01 12:34:56.";
for(int i=1; i<9; i++) {
    System.out.println(LocalDateTime.parse(date+=i, formatter1).format(formatter1));
}

date = "2023-01-01 12:34:56.1";
for(int i=1; i<9; i++) {
    System.out.println(LocalDateTime.parse(date+=i, formatter2).format(formatter2));
}

결과

MICRO_OF_SECOND: 0 ~ 6
이것은 0에서 999,999까지 초 내의 마이크로초를 계산합니다.
2023-01-01 12:34:56.1
2023-01-01 12:34:56.12
2023-01-01 12:34:56.123
2023-01-01 12:34:56.1234
2023-01-01 12:34:56.12345
2023-01-01 12:34:56.123456
2023-01-01 12:34:56.123456
2023-01-01 12:34:56.123456

NANO_OF_SECOND: 0 ~ 9
이것은 0에서 999,999,999까지 초 내의 나노초를 계산합니다.
2023-01-01 12:34:56.11
2023-01-01 12:34:56.112
2023-01-01 12:34:56.1123
2023-01-01 12:34:56.11234
2023-01-01 12:34:56.112345
2023-01-01 12:34:56.1123456
2023-01-01 12:34:56.11234567
2023-01-01 12:34:56.112345678

 

decimalPoint 의 false를 할 경우

LocalDateTime ldt = LocalDateTime.now();        
System.out.println(ldt.format(formatter2));

-> 2023-05-07 16:45:07809
        
String date = "2023-05-07 16:44:24271";  
System.out.println(LocalDateTime.parse(date, formatter2));

-> 2023-05-07T16:44:24.271