본문 바로가기
JAVA

[JAVA] 자바에서 날짜 포맷 변경하는 방법

by GoodDayDeveloper 2020. 10. 20.
반응형

 

 

안녕하세요. 오늘은 자바를 통해서 날짜 포맷을 변경하는 방법에 대해 말씀드리려 합니다.

밑에서 정리한 코드이외에도, 다른 형식의 데이트를 생성하고 싶으시면 

+1, -1 등.. 코드상의 숫자를 유기적으로 변경해주면서 활용하시면 됩니다.

자주 쓰이는 만큼 지속적으로 업데이트할 예정이니 참고해주세요!

 

 


오늘날짜(년월일)

1
2
3
4
5
6
7
8
// 오늘날짜(년월일)
public String GetTodayDate() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(System.currentTimeMillis()));
    String today = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); 
 
    return today.toString();
}
cs

 

오늘날짜(년월일시분)

1
2
3
4
5
6
7
8
9
// 오늘날짜(년월일시분)
public String GetTodayDateTime() {
    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(System.currentTimeMillis()));
    String today = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(cal.getTime()); 
 
    return today.toString();
}
 
cs

 

어제날짜

1
2
3
4
5
6
7
// 어제날짜
public String GetYesterdayDate() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, -1);
    String yesterday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); 
    return yesterday.toString();
}
cs

 

올해 년도

1
2
3
4
5
6
7
// 올해 년도
@SuppressWarnings("static-access")
public String getThisYear() {
    java.util.Calendar cal = java.util.Calendar.getInstance();
    String thisYear = String.valueOf(cal.get(cal.YEAR));
    return thisYear;
}
cs

 

현재 달

1
2
3
4
5
6
7
// 현재 달
@SuppressWarnings("static-access")
public String getThisMonth() {
    java.util.Calendar cal = java.util.Calendar.getInstance();
    String thisMonth = String.valueOf(cal.get(cal.MONTH) + 1);
    return thisMonth;
}
cs

 

 

 

 

반응형

댓글