티스토리 뷰

Server

[Java] 날짜 생성/변환

니용 2019. 12. 6. 17:14
반응형

이번에 다루어볼 내용은 Java 기본 라이브러리인 SimpleDateFormat이다. 대개 Date 클래스나 Calendar 클래스와 겸용해서 자주 사용하는데, 자바를 설치하면 기본적으로 내장되어 있고 사용법도 찾아보면 쉽게 나온다. 

 

우리 회사에서는 날짜 또는 시간에 대해 서버에서 처리하는 로직이 꽤나 많다. 시스템의 시간을 사용할 때도 있지만, AWS의 시간 또는 DB의 시간을 사용할 때도 있기 때문에 이를 환산해주는 유틸성 클래스가 따로 필요하고, 실제로도 많이 호출하는 바이다.

 

제일 먼저 정의해야 하는 것은 Timezone이다. 한국 개발자들은 "Asia/Seoul" 의 지역에 위치하고 있는 분포가 많아서 이 부분을 먼저 잡고 가면 좋겠다.

 

Timezone 세팅하기 

국가별 시간대

 

다음은 현재 일자를 구하는 함수이다.

 

 

위 코드를 사용하면 현재 타임존의 날짜를 구할 수 있다.

가령 미국이 2019년 12월 5일 22시이고, 한국이 2019년 12월 6일 12시라면 KST로 호출하게 되면 위의 주석과 같이 출력된다.

 

다음으로 많이 사용하는 것은 현재 자바 프로젝트가 올라가 있는 서버의 시간이다. AWS를 쓰므로 EC2의 시간과 같다고 생각하면 된다.

 

 

시스템 클래스에서 제공해주는 함수가 있어 이를 사용하면 밀리 세컨 단위로 나오게 된다. 이 두개를 복합적으로 사용해서 현재 시간을 구하는 방법은 아래와 같다.

 

 

위의 SimpleDateFormat에 들어가는 문자열은 말그대로 출력 형식이다.  연도(yyyy), 월(MM, 대문자로 작성한 것은 소문자 mm은 분을 가리키기 때문), 일(dd), 시(HH), 분(mm), 초(ss) 를 각각 가리키므로 원하는 형식이 있다면 순서를 바꾸어도 상관 없다.

 

날짜의 요일은 아래와 같이 구할수 있다.

 

 

마지막으로 날짜에 일수를 더하거나 빼는 것은 아래 소스를 이용하면 좋겠다.

 

왠만한 자바에서 사용하는 시간 처리는 위에 소스를 재활용하여 사용이 가능할 듯 하다.

 

 

소스 복사용

더보기

// TimeZone

public static final TimeZone TZ_KOREA = TimeZone.getTimeZone("Asia/Seoul");

 

// TimeZone 별 일자 구하기
public String getSimpleFormat(){
SimpleDateFormat dfIn = new SimpleDateFormat("yyyy-MM-dd");
dfIn.setTimeZone(TZ_KOREA);
return dfIn.format(new Date());
}

 

// 시스템 Unix Timestamp

public Long getTimestamp(){
return System.currentTimeMillis();
}

 

// Unix Timestamp가 가진 일시 구하기
public static String getDateFormat(long millsecond){
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(millsecond));
}

 

// 요일 구하기

public static String getSimpleWeekDay(String date) {

    return getWeekDay(date, "yyyy-MM-dd");
}

public static String getWeekDay(String date, String format) {
    try {
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.KOREAN);
            Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Seoul"));
            cal.setTime(sdf.parse(date));
            int day = cal.get(Calendar.DAY_OF_WEEK);
            switch (day) {
                case 1: return "일";
                case 2: return "월";
                case 3: return "화";
                case 4: return "수";
                case 5: return "목";
                case 6: return "금";
                case 7: return "토";
                default : return "";
            }
    } catch (Exception e) {
            e.printStackTrace();
    }
    return "";
}

 

// 파라미터를 받아 days 만큼의 일자를 증가시켜 반환
// return String(YYYY-MM-DD 00:00:00)
public static String getPlusDate(String param, int days){
try {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Asia/Seoul"));
if(param != null){
int year = Integer.parseInt(param.substring(0, 4));
int month = Integer.parseInt(param.substring(5, 7))-1;
int day = Integer.parseInt(param.substring(8, 10));
cal.set(year,month,day);
}
cal.add(Calendar.DATE, days);
return new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
} catch (Exception e) {}
return param;
}

// 파라미터를 받아 days 만큼의 일자를 증가시켜 타임스탬프 값을 반환
// return String(YYYY-MM-DD 00:00:00)
public static String getPlusTimestamp(String param, int days){
String plusDate = getPlusDate(param, days);
return plusDate + param.substring(plusDate.length());
}

 


2019-12-26 추가

더보기

/**
* 비교 대상 시간이 현시점 이후 시간인지 체크
* @param compareTime
* @return
*/
public static boolean isAfterTime(String compareTime) {
try {
Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(compareTime);
return new Date().getTime() < endTime.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 비교 대상 날짜가 현재 날짜 이후인지 체크
* @param compareDay
* @return
*/
public static boolean isAfterDay(String compareDay) {
try {
Date endDay = new SimpleDateFormat("yyyy-MM-dd").parse(compareDay);
return new Date().getTime() < endDay.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 오늘 날짜가 비교대상 시간 사이인지 체크
* @param fromDay
* @param toDay
* @return
*/
public static boolean isBetweenDate(String fromDay, String toDay) {
try {
Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(fromDay);
Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(toDay);
return new Date().getTime() < (endTime.getTime() + plusMillis) && new Date().getTime() >= startTime.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 현재 시간이 비교대상 시간 사이인지 체크
* @param fromTime
* @param toTime
* @return
*/
public static boolean isBetweenTime(String fromTime, String toTime) {
try {
Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fromTime);
Date endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(toTime);
return new Date().getTime() < endTime.getTime() && new Date().getTime() >= startTime.getTime();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

/**
* 오늘 구하기
* @return
*/
public static String getToday() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}

/**
* 어제 날짜 구하기
* @return
*/
public static String getYesterday() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date().getTime() - TimeUnit.DAYS.toMillis(1));
}

/**
* 현재 시간 구하기
* @return
*/
public static String getCurrentTimestamp() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}

반응형

'Server' 카테고리의 다른 글

[Java] MultipartFile 를 이용하여 파일 업로드하기  (0) 2020.01.28
[Java] Cron 표현식  (0) 2019.12.19
SQL에 대해 알아보자  (0) 2019.12.15
[Java] 엑셀 변환  (0) 2019.12.03
[Java] ORM과 JPA, 그리고 Hibernate  (0) 2019.11.28
[Java] NPE와 Optional Class  (1) 2019.10.26
댓글
공지사항