JAVA
밀리초 4자리까지 가져와서 포맷팅하기
ez.pang
2023. 11. 7. 09:45
SAP 에 인터페이스 할 일이 있는데
보내야할 데이터 중 yyMMddHHmmssSSSS 형식의 데이터에 5자리 시퀀스를 붙여서 만들어야할게 있었다.
근데
// tip: each public class is put in its own file
import java.text.SimpleDateFormat;
import java.util.Date;
public class main
{
// tip: arguments are passed via the field below this editor
public static void main(String[] args)
{
int seq = 1;
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmssSSSS");
String formattedDate = dateFormat.format(currentDate);
// 정수를 0을 붙여 6자리 문자열로 변환
String numberString = String.format("%05d", seq);
System.out.println(formattedDate+numberString);
}
}
흔히들 쓰는 java.util.Date 를 java.text.SimpleDateFormat 으로 포맷팅하면
231107004444047100001
이런식으로 밀리초는 3자리까지만 측정하고 맨 앞은 0을 채워넣기만 한다. (굉장히 킹받음)
멍청한 챗GPT 한테 물어봐도 답변이 그지같아서 인터넷 발품으로 겨우 알아냄..
해답은 java.time.Instant 였다.
Instant에 대한 설명은 아래 블로그가 깔쌈하다.
Java 8 LocalDateTime vs Instant 어떤 상황에서 쓰는게 적합한가?
Java 8 LocalDateTime vs Instant 어떤 상황에서 쓰는게 적합한가? 들어가기 전에 본 글은 세션 공유용 자료이며 LocalDateTime, Instant 의 개념에 관한 짧은 글이 아니므로 양해 부탁드립니다. 포스팅 계기 최
sujl95.tistory.com
// tip: each public class is put in its own file
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class main
{
// tip: arguments are passed via the field below this editor
public static void main(String[] args)
{
int seq = 14;
Instant instant = Instant.now();
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("UTC"));
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyMMddHHmmssSSSS");
String formattedDate = dateFormat.format(zonedDateTime);
// 정수를 0을 붙여 6자리 문자열로 변환
String numberString = String.format("%05d", seq);
System.out.println(formattedDate);
System.out.println(formattedDate+numberString);
}
}
암튼 이렇게 하면 yyMMddHHmmssSSSS 까지 받아올 수 있다.