Java에서 시간 관련 스크립트 사용하기

Calendar 클래스를 활용한 날짜 조작

1. Calendar 설정 및 날짜 조작

1.1 날짜 더하기/빼기


java.util.Date currentDate = new java.util.Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(currentDate);
calendar.add(Calendar.DATE, -1); // 날짜를 하루 전으로 이동
currentDate = calendar.getTime();
java.sql.Date sqlDate = new java.sql.Date(currentDate.getTime()); // 시분초 정보 제거

1.2 Java에서 날짜에 일수 추가하기


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
System.out.println(date);

Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, 4);
Date newDate = calendar.getTime();
System.out.println(newDate);
String newFormattedDate = sdf.format(newDate);
System.out.println(newFormattedDate);

1.3 사업 결산 기간 얻기


Calendar c = Calendar.getInstance();
int quarter = (c.get(Calendar.MONTH) + 3) / 3;
fzAcc.setAccWorkPeriod("0" + quarter + "Q");

// 연도별 결산 기간
LocalDateTime now = LocalDateTime.now();
fzAcc.setAccWorkPeriodYear(String.valueOf(now.getYear()));

1.4 현재 시간을 기준으로 지난 주, 달, 년의 시간 얻기


SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();

// 지난 7일
c.setTime(new Date());
c.add(Calendar.DATE, -7);
Date d = c.getTime();
String day = format.format(d);
System.out.println("지난 7일: " + day);

// 지난 1개월
c.setTime(new Date());
c.add(Calendar.MONTH, -1);
Date m = c.getTime();
String mon = format.format(m);
System.out.println("지난 1개월: " + mon);

// 지난 3개월
c.setTime(new Date());
c.add(Calendar.MONTH, -3);
Date m3 = c.getTime();
String mon3 = format.format(m3);
System.out.println("지난 3개월: " + mon3);

// 지난 1년
c.setTime(new Date());
c.add(Calendar.YEAR, -1);
Date y = c.getTime();
String year = format.format(y);
System.out.println("지난 1년: " + year);

1.5 Calendar 클래스로 현재 달의 첫날과 마지막 날, 최근 3개월 범위, 분기 범위 얻기


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
String endDate = sdf.format(calendar.getTime());
System.out.println(endDate);

// 최근 12개월의 마지막 날
for (int i = 1; i <= 12; i++) {
    calendar.add(Calendar.MONTH, -1);
    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    endDate = sdf.format(calendar.getTime());
    System.out.println(endDate);
}

1.6 Calendar로 현재 연도, 월, 날짜 얻기


Calendar cale = Calendar.getInstance();
int year = cale.get(Calendar.YEAR);
int month = cale.get(Calendar.MONTH) + 1;
int day = cale.get(Calendar.DATE);

System.out.println("현재 날짜: " + cale.getTime());
System.out.println("연도: " + year);
System.out.println("월: " + month);
System.out.println("일: " + day);

// 현재 달의 첫날과 마지막 날
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
cale.set(Calendar.DAY_OF_MONTH, 1);
String firstDay = format.format(cale.getTime());

cale.set(Calendar.DAY_OF_MONTH, cale.getActualMaximum(Calendar.DAY_OF_MONTH));
String lastDay = format.format(cale.getTime());

System.out.println("현재 달의 첫날과 마지막 날: " + firstDay + " and " + lastDay);

문자열을 날짜로 변환하기


public static Date strToDate(String str) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    if (str.indexOf('年') > -1 && str.indexOf('月') > -1 && str.indexOf('日') > -1) {
        format = new SimpleDateFormat("yyyy年MM月dd日");
    } else if (str.indexOf('年') > -1 && str.indexOf('月') > -1 && str.indexOf('号') > -1) {
        format = new SimpleDateFormat("yyyy年MM月dd号");
    }
    Date date = null;
    try {
        date = format.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

JDK 7에서 날짜의 연도, 월, 일을 얻기


String year1 = String.format("%tY", startDate);
String year2 = String.format("%tY", endDate);
String month1 = String.format("%tm", startDate);
String month2 = String.format("%tm", endDate);
String day1 = String.format("%td", startDate);
String day2 = String.format("%td", endDate);

JDK 8에서 새롭게 도입된 시간 관련 함수와 사용법

4.1 LocalDateTime


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;

public class Test2 {
    public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime = LocalDateTime.now().minus(1, ChronoUnit.MONTHS);
        System.out.println(localDateTime.format(dateTimeFormatter));
    }
}

타임스탬프 사용하기

1. 방법 1


long startTime = System.currentTimeMillis(); // 코드 실행 전 시간
BigDecimal exch = null;
for (int i = 0; i <= 400; i++) {
    exch = dataDictionaryService.getExch("CNY", "CNY", date);
}

long endTime = System.currentTimeMillis(); // 코드 실행 후 시간
Calendar c = Calendar.getInstance();
c.setTimeInMillis(endTime - startTime);
System.out.println("소요 시간: " + c.get(Calendar.MINUTE) + "분 "
        + c.get(Calendar.SECOND) + "초 " + c.get(Calendar.MILLISECOND) + "밀리초");

2. 방법 2


package com.asd.common.utils.datetag;

import java.util.Date;

public class DateTag {
    private Date startDate;
    private Date lastDate;
    private StringBuilder info = new StringBuilder();
    private int messageIndex = 0;

    public DateTag(String message) {
        this.lastDate = new Date();
        this.startDate = new Date();
        info.append(message);
        info.append(":");
        this.messageIndex = message.length() + 1;
    }

    public void appendDate(String message) {
        info.append(message);
        info.append(":");
        info.append(new Date().getTime() - lastDate.getTime());
        info.append(";");
        this.lastDate = new Date();
    }

    public void addFist(String message) {
        info.insert(messageIndex, ";");
        info.insert(messageIndex, new Date().getTime() - startDate.getTime());
        info.insert(messageIndex, ":");
        info.insert(messageIndex, message);
        this.lastDate = new Date();
    }

    public String getInfo() {
        return info.toString();
    }
}

DateTag tag = new DateTag("sss");
BigDecimal ss = exch == null ? BigDecimal.ZERO : exch.getExchRate().divide(new BigDecimal(exch.getBase()));
tag.appendDate("데이터 필드에서 가져오는 데 걸린 시간");
tag.addFist("총 소요 시간");
System.out.println(tag.getInfo());

3. 방법 3


StopWatch sw = new StopWatch("계약 검사 목록 내보내기");
sw.start("기본 데이터 가져오기");
TreatyCheckListSheets sheets = prepareBaseData(treatyIds);
sw.stop();
sw.start("데이터 내보내기");
exportCheckList(sheets, response);
sw.stop();
System.out.println(sw.prettyPrint());

태그: java Calendar SimpleDateFormat LocalDateTime ChronoUnit

9월 12일 01:16에 게시됨