Day25 :) 포맷팅

Nux·2021년 10월 8일
0

자바웹개발

목록 보기
25/105
post-thumbnail

포맷팅

  • 숫자, 날짜, 문자 간 상호 변환하는것
    • 날짜(Date) ↔ 문자열(String)
    • 숫자(int, double) ↔ 문자열(String) 등

날짜 포맷팅

  • import java.util.Date;
기호내용
y
M
d
E요일
a오전/오후
H시간(0~23)
h시간(1~12)
m분(0~59)
s초(0~59)
S밀리초(0~999)
  • Date 메서드의 형식기호. 대소문자 구분 있음

주요 메서드

Date 기본객체

  • 요일 월 일 시:분:초 기준시간대 연도 순으로 시간 표시
Date date = new Date();
System.out.println(date);
// 출력값 Fri Oct 08 21:27:25 KST 2021

SimpleDateFormat

  • Date를 지정된 형식의 String으로 반환
    • import java.text.SimpleDateFormat;
    • .applyPattern("형식"): 출력할 Date에 해당 형식을 적용시킴
SimpleDateFormat a = new SimpleDateFormat();
a.applyPattern("형식");	// "형식"패턴을 a(SimpleDateFormat)에 적용시킴
String b = a.format(date);	// a의 format을 String으로 변환하여 b에 대입
System.out.println(b);
// "형식"대로 날짜가 출력됨
SimpleDateFormat ex1 = new SimpleDateFormat();
ex1.applyPattern("yyyy-MM-dd");
String date1 = ex1.format(date);
System.out.println(date1);
// 출력값: 2021-10-08
ex1.applyPattern("a h시 m분 s초");
String date2 = ex1.format(date);
System.out.println(date2);
// 출력값: 오후 9시 30분 25초
ex1.applyPattern("yyyy년 MM월 dd일 EEEE");
String date3 = ex1.format(date);
System.out.println(date3);
// 출력값: 2021년 10월 8일 금요일

Date parse("text")

  • text를 Date형식으로 변환하여 반환
String text1 = "1976-04-02"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birthday = sdf.parse(text1);
// "1976-04-02"이 String에서 Date로 형변환됨

숫자포맷팅

  • import java.text.DecimalFormating;

주요 메서드

DecimalFormat

  • 숫자를 지정된 패턴의 String으로 변환
기호내용
0숫자
#숫자
.소수점
,자리수 구분
  • 주요 형식기호
long ex1 = 10000000000L // 백억

DecimalFormat a = new DecimalFormat("##,###");	// "00,000"으로 표시 가능
String text1 = a.format(ex1)	// ex1(long)를 String으로 형변환
System.out,println(text1);
// 출력값: 10,000,000,000
double ex2 = 1234.567;

a.applyPattern("##,###.#");		// "00,000.0"으로 표시 가능
String text2 = a.format(ex2);
System.out.println(text2);
// 출력값: 1,234.6

String

메서드리턴타입
parse기본자료형
valueOf객체

숫자👉문자열

  • String.valueOf(숫자)

문자열👉숫자

  • Integer.parseInt("문자")
  • Integer.valueOf("문자")
    • 오토언박싱으로 객체->기본자료형으로 자동변환

메세지 포맷팅

  • import java.text.MessageFormat;

응용

Object[] a = {"류승룡", "마동석", "조진웅};
MessageFormat ex1 = new MessageFormat("직급: {0}대표님, {1}사장님, {2}이사님");
String text1 = ex1.format(a);	// ex1의 포맷에 배열 a를 집어넣음
System.out.println(text1);
// 출력값 -> 직급: 류승룡대표님, 마동석사장님, 조진웅이사님
더 간단하게
String text2 = MessageFormat.format("직급: {0}대표님, {1}사장님, {2}이사님", a);
System.out.println(text2);
// 출력값 -> 직급: 류승룡대표님, 마동석사장님, 조진웅이사님

0개의 댓글