메뉴 건너뛰기

조회 수 5233 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
날짜와 시간을 원하는 포맷으로 제어하거나 연산하여 결과값을 얻는 클래스

※ 필요 라이브러리 : 아파치그룹 commons 프로젝트에서 commons-lang 을 사용한다. 아래 첨부물을 받거나 해당 프로젝트 사이트에서 받으면 됩니다.

commons-lang-2.5.jar
날짜와 시간을 원하는 포맷의 결과를 문자열 형태로 반환받으며, 정규화식과 SimpleDateFormat 를 이용한다.
시작시간과 종료시간을 이용하여 간격을 구하거나, 두 시간의 합을 구할 수 있다.


 날짜 시간 클래스 : DateUtils.java


/**
 * @class DateUtils ver 1.0.0
 * @brief 날짜와 시간을 제어함
 *
 * registered date 20081217
 * programmed by Seok Kyun. Choi. (최석균)
 * http://syaku.tistory.com
 */

package com.syaku.core.util;

import java.util.*;
import java.util.regex.*;
import java.text.*;

import org.apache.commons.lang.StringUtils;

public class DateUtils extends StringUtils {

  private static SimpleDateFormat formatter;
  private static DecimalFormat df;

  /**
  * @method : getDate(parameter,parameter2)
  * @brief : 정규표현식을 이용하여, 날짜를 제어한다. 각 시분초는 구분자가 있어야 한다.
  * @parameters {
        parameter : (String) $1 = 년 , $2 = 월 , $3 = 일 , $4 = 시 , $5 = 분 , $6 = 초
        parameter2 : (String) 구분자(-_:./\s) 를 가진 날짜
      }
  * @return : (String) 정규표현식 시간 || 00:00:00
  */
  public static String getDate(String patten,String date) {
    if (isEmpty(date)) return date;
    String sysdate_patten = "(^[0-9]*)[-_:.\\/\\s]?([0-9]*)[-_:.\\/\\s]?([0-9]*)[-_:.\\/\\s]?([0-9]*)[-_:.\\/\\s]?([0-9]*)[-_:.\\/\\s]?([0-9]*)(.*)$";
    Pattern date_comp = Pattern.compile(sysdate_patten);
    if (date_comp.matcher(date).find()) return date.replaceAll(sysdate_patten,patten);
    else return getDate(patten,"00:00:00");
  }

  /**
  * @method : setDate(parameter)
  * @brief : 날짜를 설정하고 Date 객체로 반환한다.
  * @parameters {
        parameter : (String) 날짜
      }
  * @return : (Date)
  */
  public static Date setDate(String date) throws Exception {
    date = date("yyyy-MM-dd HH:mm:ss",date);
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return (Date) formatter.parse(date);
  }

  /**
  * @method : getTime(parameter,parameter2)
  * @brief : 정규표현식을 이용하여, 시간을 제어한다. 각 시분초는 구분자가 있어야 한다.
  * @parameters {
        parameter : (String) $1 = 시 , $2 = 분 , $3 = 초
        parameter2 : (String) 구분자(-_:./\s) 를 가진 시간
      }
  * @return : (String) 정규표현식 시간 || 00:00:00
  */
  public static String getTime(String patten,String time) {
    if (isEmpty(time)) return time;
    String time_patten = "(^[0-9]*)[-_:.\\/\\s]?([0-9]*)[-_:.\\/\\s]?([0-9]*)(.*)$";
    Pattern time_comp = Pattern.compile(time_patten);
    if (time_comp.matcher(time).find()) return time.replaceAll(time_patten,patten);
    else return getTime(patten,"00:00:00");
  }

  /**
  * @method : setTime(parameter)
  * @brief : 시간을 설정하고 Date 객체로 반환한다.
  * @parameters {
        parameter : (String) 시간
      }
  * @return : (Date)
  */
  public static Date setTime(String time) throws Exception {
    time = time("HH:mm:ss",time);
    formatter = new SimpleDateFormat("HH:mm:ss");
    return (Date) formatter.parse(time);
  }

  /**
  * @method : date(parameter, parameter2)
  * @brief : SimpleDateFormat 이용하여 날짜를 반환한다.
  * @parameters {
       parameter : (String) SimpleDateFormat 클래스의 포맷
       parameter2 : (String || Date) SimpleDateFormat 포맷 시간
     }
  * @return : (String) 날짜
  */
  public static String date() throws Exception {
    return date("yyyy-MM-dd HH:mm:ss");
  }
  public static String date(String format) throws Exception {
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = formatter.format(new Date());
    return date(format,date);
  }
  public static String date(String format, Date date) throws Exception {
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return date(format,formatter.format(date));
  }
  public static String date(String format, String date) throws Exception {
    if (isEmpty(format)) format = "yyyy-MM-dd HH:mm:ss";
    if (isEmpty(date)) return null;

    date = date.replaceAll("[^0-9]+","");
    date = rightPad(date,14,'0');
    date = date.replaceAll("(^[0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})","$1-$2-$3 $4:$5:$6");
    formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date redate = formatter.parse(date);
    formatter = new SimpleDateFormat(format);
    return formatter.format(redate);
  }


  /**
  * @method : time(parameter, parameter2)
  * @brief SimpleDateFormat 이용하여 날짜를 반환한다.
  * @parameters {
        parameter : (String) SimpleDateFormat 클래스의 포맷
        parameter2 : (String || Date) SimpleDateFormat 포맷 시간
    }
  * @return : (String) 시간
  */
  public static String time() throws Exception {
    return time("HH:mm:ss");
  }
  public static String time(String format) throws Exception {
    formatter = new SimpleDateFormat("HH:mm:ss");
    String time = formatter.format(new Date());
    return time(format,time);
  }
  public static String time(String format, String time) throws Exception {
    time = time.replaceAll("[^0-9]+","");
    time = rightPad(time,6,'0');
    time = leftPad(time,14,'0');
    return date(format,time);
  }
  /**
  * @method : timespace(parameter, parameter2,parameter3)
  * @brief 시작시간과 종료시간의 간격을 구합니다.
  * @parameters {
        parameter : (String) 시작시간
        parameter2 : (String) 종료시간
        parameter3 : (String) SimpleDateFormat 클래스의 포맷
    }
  * @return : (String) SimpleDateFormat 포맷 시간
  */
  public static String timespace(String stime, String etime) throws Exception {
    return timespace(stime,etime,"HH:mm:ss");
  }
  public static String timespace(String stime, String etime, String format) throws Exception {
    try {
      if (isEmpty(stime) || isEmpty(etime)) throw new Exception("parameter null");

      stime = stime.replaceAll("[^0-9]+","");
      etime = etime.replaceAll("[^0-9]+","");

      int s = Integer.parseInt(stime);
      int e = Integer.parseInt(etime);
      stime = rightPad(stime,6,'0');
      etime = rightPad(etime,6,'0');
      stime = date("yyyy-MM-dd HH:mm:ss","19700101" + stime);
      etime = date("yyyy-MM-dd HH:mm:ss","19700101" + etime);

      formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date sdate = formatter.parse(stime);
      Date edate = formatter.parse(etime);
      // 9시간 (540*60*1000 = 32400000) 오차 제거하기
      Long ret = (edate.getTime() - sdate.getTime()) - 32400000;
      String ext = formatter.format(ret);

      return date(format,ext);
    } catch (Exception e) {
      return time(format,"000000");
    }
  }
  /**
  * @method : timeAdd(parameter, parameter2,parameter3)
  * @brief 구분자를 포함한 두 시간을 합산합니다. 분 초 중에 60 이상인 경우 시간 혹은 분을 반올림합니다.
  * @parameters {
        parameter : (String) 구분자(-_:./\s)를 가진 사간
        parameter2 : (String) 구분자(-_:./\s)를 가진 시간
        parameter3 : (String)  $1 = 시 , $2 = 분 , $3 = 초
    }
  * @return : (String) 정규표현식 시간 : 00:00:00
  */
  public static String timeAdd(String time,String time2,String patten) throws Exception {
    String ret = "00:00:00";
    if (isEmpty(patten)) patten = "$1:$2:$3";

    int sh = Integer.parseInt(getTime("$1",time));
    int sm = Integer.parseInt(getTime("$2",time));
    int ss = Integer.parseInt(getTime("$3",time));
    int eh = Integer.parseInt(getTime("$1",time2));
    int em = Integer.parseInt(getTime("$2",time2));
    int es = Integer.parseInt(getTime("$3",time2));

    try {
      int h = sh + eh;
      int s = ss + es;
      int m = 0;
      if (s > 60) { 
        Double mm = Math.floor(s/60);
        df = new DecimalFormat("0"); 
        int mmm = Integer.parseInt(df.format(mm));

        s = s - (mmm * 60); 
        m = m + mmm;
      }

      m = m + sm + em;
      if (m > 60) { 
        Double hh = Math.floor(m/60);
        df = new DecimalFormat("0"); 
        int hhh = Integer.parseInt(df.format(hh));

        m = m - (hhh * 60); 
        h = h + hhh;
      }

      ret = leftPad(Integer.toString(h),2,'0') + ":" + leftPad(Integer.toString(m),2,'0') + ":" + leftPad(Integer.toString(s),2,'0');
    } catch (Exception e) {
      ret = "00:00:00";
    }

    return getTime(patten,ret);
  }

}




 샘플소스
<%@ page contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.*" %>
<%@ page import="com.syaku.core.util.DateUtils" %>
<h2> DateUtils.date()</h2>
<%
String today = DateUtils.date();
out.println("오늘날짜 : " + today);
// 오늘날짜 : 2010-04-27 10:56:32 
%>
<br />
<%
out.println("new Date() => yyyy/MM/dd : " + DateUtils.date("yyyy/MM/dd"));
// new Date() => yyyy/MM/dd : 2010/04/27 
%>
<br />
<%
out.println("2010103004 => yyyy년도 MM월 HH시간입니다 : " + DateUtils.date("yyyy년도 MM월 HH시간입니다","2010103004"));
// 2010103004 => yyyy년도 MM월 HH시간입니다 : 2010년도 10월 04시간입니다
%>
<h2> DateUtils.setDate()</h2>
<%
Date date = DateUtils.setDate(today);
out.println("getTime : " + date.getTime());
// getTime : 1272333392000 
%>
<br />
<%
out.println("yyyy 년도 : " + DateUtils.date("yyyy 년도",date));
// yyyy 년도 : 2010 년도
%>
<h2> DateUtils.time()</h2>
<%
String nowtime = DateUtils.time();
out.println("현재시간 : " + nowtime);
// 현재시간 : 10:56:32 
%>
<br />
<%
out.println("new Date() => KK:mm:ss : " + DateUtils.time("KK:mm:ss"));
// new Date() => KK:mm:ss : 10:56:32 
%>
<br />
<%
out.println("14:20:10 => hh시간입니다 : " + DateUtils.time("hh시간입니다","14:20:10"));
// 14:20:10 => hh시간입니다 : 02시간입니다
%>
<h2> DateUtils.setTime()</h2>
<%
Date time = DateUtils.setTime(nowtime);
out.println("getHours : " + time.getHours());
// getHours : 10
%>
<h2> DateUtils.timeAdd()</h2>
<%
String addtime = DateUtils.timeAdd("100:20:10","150:50:30","$1시간이며, $2분입니다.");
out.println("100:20:10 + 150:50:30 더한 시간은 " + addtime);
// 100:20:10 + 150:50:30 더한 시간은 251시간이며, 10분입니다.
%>

<h2> DateUtils.timespace()</h2>
<%
String timespace = DateUtils.timespace("22:20:10","07:50:30","HH:mm:ss");
out.println("22:20:10 ~ 07:50:30 간격은 " + timespace);
// 22:20:10 ~ 07:50:30 간격은 09:30:20
%>





List of Articles
번호 제목 날짜 조회 수
71 enum 2016.09.13 3404
70 문자 기반 스트림 2016.09.13 3440
69 쓰레드의 우선순위 2016.09.13 3503
68 파일I/O 개요 file 2016.09.13 3507
67 Jadclipse 플러그인 설치 file 2016.09.19 3512
66 인터페이스와 다형성 2016.09.13 3535
65 File 클래스 file 2016.09.13 3603
64 원하는 패턴의 날짜 구하기 : JAVA 2016.12.09 3608
63 새로 만든 모듈의 iBatis 쿼리를 새로운 xml 파일에 만들고 싶다면 이렇게 하자. file 2016.08.29 3655
62 set get 파라미터 2016.08.18 3658
61 컬렉션 프레임워크 file 2016.09.13 3705
60 JAR 파일 2016.09.19 3713
59 BigDecimal타입의 사칙연산 2016.12.22 3713
58 클래스 메서드와 인스턴스 메서드 2016.09.13 3720
57 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동]3. 이클립스 설치 file 2016.08.18 3756
56 바이트 기반의 스트림 file 2016.09.13 3763
55 static멤버와 관련된 예제 2016.09.21 3768
54 새로 만든 모듈의 iBatis 쿼리를 새로운 xml 파일에 만들고 싶다면 이렇게 하자. file 2016.08.29 3773
53 [자바(스프링&mybatis&jsp) 프로젝트 & 아파치 &톰켓 연동 ] 이클립스 프로젝트 생성 순서07.commons-collection 설치 file 2016.08.18 3845
52 Select statements cannot be executed as an update. 에러 해결방법 file 2016.08.29 3853
Board Pagination Prev 1 2 3 4 5 6 7 8 Next
/ 8

하단 정보를 입력할 수 있습니다

© k2s0o1d4e0s2i1g5n. All Rights Reserved