참고
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
SimpleDateFormat (Java Platform SE 8 )
Parses text from a string to produce a Date. The method attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all charac
docs.oracle.com
Format 하기 전
현재 날짜를 Date 인스턴스를 통해 가져온 후, 출력하면 아래와 같다.
코드
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now);
}
}
결과
하지만 영어 말고 숫자로 표현하고 싶을 수도 있고, 밀리초까지 구하고 싶을 때도 있다. 이럴 때 쓸 수 있는 것이 SimpleDateFormat이다.
Format 한 후
yyyy-MM-dd hh:mm:ss 로 포맷을 한 후 출력해보자. 월(Month)과 분(minute)를 구분하기 위해 대소문자를 구별해주어야 한다. format 함수를 호출해 포맷해주었다.
코드
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(format.format(now));
}
}
결과
패턴
주로 'yyyy-MM-dd HH:mm:ss' 만 알면 문제될 건 없을거 같은데, 혹시 모르니 다른 패턴도 한번 봐두면 좋을 것 같다. 위에 링크된 문서에서 몇 개 가져와 한글로 적어놓은 것인데 더 궁금하면 문서를 확인하면 된다.
패턴 | 의미 | 표현 | 출력 |
G | 연대(BC, AD) | Text | AD |
y | 년도 | Year | 2023 |
M | 월 | Month | 8 |
w | 해당 년도의 몇 번째 주 | Number | 27 |
W | 해당 월의 몇 번째 주 | Number | 2 |
D | 해당 년도의 몇 번째 일 | Number | 189 |
d | 해당 월의 몇 번째 일 | Number | 10 |
F | 해당 월의 몇 번째 요일(1 ~ 5) | Number | 2 |
E | 요일(월 ~ 일) | Text | Tue |
a | 오전/오후 | Text | PM |
H | 시간(0 ~ 23) | Number | 20 |
h | 시간(1 ~ 12) | Number | 4 |
m | 분(0 ~ 59) | Number | 2 |
s | 초(0 ~ 59) | Number | 55 |
S | 밀리초(0 ~ 999) | Number | 978 |
z | 타임존 | General time zone | Pacific Standard Time; PST; GMT-08:00 |
Z | 타임존(RFC 822) | RFC 822 time zone | -0000 |
문자열 사용하기
위에는 Date 인스턴스를 직접 생성했지만, "2023-08-24 04:58:03.01" 이와 같은 문자열을 입력 받아 처리해야 하는 경우도 있다. 이때는 SimpleDateFormat 인스턴스를 생성하고, parse() 함수를 사용해 문자열을 Date로 변환해준 뒤 위와 같이 해주면 된다.
코드
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String now_str = "2023-08-24 12:13:00";
Date now = format.parse(now_str);
System.out.println(format.format(now));
}
}
결과
'Study > Programming Language' 카테고리의 다른 글
[C++] cout << 을 사용해 화면 출력하기 (0) | 2024.05.03 |
---|---|
[C] typedef: typedef의 사용법과 특징, 구조체 활용 (2) | 2024.03.23 |
[C] 공용체(Union): 공용체 정의와 공용체 변수 선언, 초기화 (1) | 2024.03.23 |
[C] 구조체: 구조체 정의와 구조체 변수 선언, 초기화 (1) | 2024.03.22 |
[Java] Java에서 EOF 다루는 방법 (0) | 2023.09.25 |