Language/자바

[자바]3. 날짜 출력 Date

추억을 백앤드하자 2021. 3. 23. 08:33
728x90
반응형
SMALL

Date()는 컴퓨터의 현재 날짜를 읽어 Date 객체로 만든다

특정 문자열 포맷으로 얻고 싶다면 java.text.SimpleDateFormat 클래스를 이용하자

 

*SimpleDateFormat를 용한 포멧

package thisisjava;

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatExample {
	public static void main(String[] args) {
		Date now=new Date();
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		System.out.println(sdf.format(now));
		
		sdf=new SimpleDateFormat("yyyy년 MM월 dd일");
		System.out.println(sdf.format(now));
		
		sdf=new SimpleDateFormat("yyyy.MM.dd a HH:mm:ss");
		System.out.println(sdf.format(now));
		
		sdf=new SimpleDateFormat("오늘은 E요일");
		System.out.println(sdf.format(now));
		
		sdf=new SimpleDateFormat("올해의 D번째 날");
		System.out.println(sdf.format(now));
		
		sdf=new SimpleDateFormat("이달의 d번째 날");
		System.out.println(sdf.format(now));
	}

}

패턴 문자 의미 패턴 문자 의미
y H 시(0~23)
M h 시(1~12)
d K 시(0~11)
D 월 구분 없는 일(1~365) k 시(1~24)
E 요일 M
a 오전/오후 s
w 년의 몇 번째 주 S 밀리세컨드(1/1000초)
W 월의 번 번째 주    

 

*DateTimeFormatter을 이용한 포맷

package thisisjava;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatExample {
	public static void main(String[] args) {
		LocalDateTime now =LocalDateTime.now();
		DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy년 M월 d일 a h시 m분");
		String nowString =now.format(dtf);
		System.out.println(nowString);
	}
}

 

728x90
반응형
LIST