ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Java 날짜 관련 메소드 정리 (SimpleDateFormat, parse(), format())
    Java 2023. 8. 11. 19:23

    Date 클래스를 사용하다보면, 원하는 날짜 형식을 얻기 어렵다. 그래서 원하는 날짜 포맷을 얻기 위해서는 java.text.SimpleDateFormat 클래스를 이용하는 경우가 있다.

     

    * format()

    • date 형식의 데이터를 문자열로 전환해준다.
    // 사용법
    Date today = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String dateStr = dateFormat.format(today);

     

    * parse()

    • 파라미터로 받은 문자열을 date 타입의 객체로 전환해준다.
    // 사용법
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date date = dateFormat.parse(dateStr);

     

    * 실제 사용하는 경우

    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Main {
    	public static void main(String[] args) {
    	    Date today = new Date();
    	    System.out.println(today);
    	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");   // Tue Aug 08 05:33:58 GMT 2023
    	    System.out.println(dateFormat.format(today));   // 2023-08-08
    	    
    	    // 날짜 형식 변환시 parsing 오류를 try catch로 체크
    	    try {
    	        String tDay = "20230808";
    	        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    	        Date temp = format.parse(tDay);
    	        System.out.println(dateFormat.format(temp));   // 2023-08-08   
    	    } catch (ParseException e) {
    	        e.printStackTrace();
    	    }
    
    	}
    }

     

    * 두 날짜의 차이 구하기

    public class Main {
    	public static void main(String[] args) {
    	    try {
    	        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    	        
                String start = "2023-02-01";
                String end = "2023-01-01";
                
                Date startDate = new Date(dateFormat.parse(start).getTime());
                Date endDate = new Date(dateFormat.parse(end).getTime());
    	        
    	        long calculate = endDate.getTime() - startDate.getTime();
    	        int days = (int)(calculate / ( 24*60*60*1000));    
    	        
    	        System.out.println(days);   // 양수면 end가 더 나중 날짜, 음수면 end가 더 이른 날짜로 판단
    	    } catch (ParseException e) {
    	        e.printStackTrace();
    	    }
    	}
    }
Designed by Tistory.