[JAVA] Date - SimpleDateFormat

MinHee·2023년 3월 2일
0
post-thumbnail

string to date

	import java.text.SimpleDateFormat;

	SimpleDateFormat sd = new SimpleDateFormat("HH:mm");
	String time_str = "23:23";

try{

	Date date = sd.parse(time_str);

}catch(Exception e){

}

date to string

	import java.text.SimpleDateFormat;
    
	Date date = new Date(); //현재 시간 저장
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일");
    String str = sdf.format(date);

SimpleDateFormat

string to date / date to string 변환에 사용되는 클래스
-> java.text 클래스 내부에 존재

SimpleDateFormat to Date 객체 변환 시 parse();

SimpleDateFormat.parse(new String())
반환형 : Date 객체
입력 : String

java: unreported exception java.text.ParseException; must be caught or declared to be thrown

try-catch 문 내에서 호출하지 않을 시 위와 같은 오류 발생, 실행 안됨
-> 반드시 아래와 같이 예외 처리문 내에서 호출

try{

	Date date = sd.parse(time_str);

}catch(ParseException e){
	  e.printStackTrace();
}

Date to String 객체 변환 시 format();

SimpleDateFormat.format(new Date())
반환형 : String
입력 : Date 객체

	Date date = new Date(); //현재 시간 저장
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일");
    String str = sdf.format(date);
    
    System.out.println(date);
    System.out.println(str);

Date

java.util 클래스 내부에 존재하는 날짜 다루는 클래스

long time = date.getTime();

getTime() : 시간을 밀리초 단위로 변환하여 출력

long result += (end.getTime() - start.getTime()) / 60000; //분 단위

Time

profile
성장하는 개발자

0개의 댓글