본문 바로가기

프로그래밍/자바(java)

[자바/java] Math클래스, Date 클래스

Math 클래스

 

math 클래스는 수학에서 사용할 수 있는 메소드를 제공하고 있다.

 

public class MathMain {
    public static void main(String[] args) {

        // Math.abs -- 절댓값 표시
        double PI = Math.abs(-3.14);

        // Math.ceil - 안에 숫자 보다 큰 수중 가장 작은 정수 (올림)
        double ceil1 = Math.ceil(3.14);
        double ceil2 = Math.ceil(-3.14);


        // Math.floor - 숫자 보다 작은 큰 수중에 가장 큰 정수 (내림)
        double floor1 = Math.floor(3.14);
        double floor2 = Math.floor(-3.14);

        // Math.max 두 수 중에 최대값
        int max = Math.max(20, 30);

        // Math.min 두 수 중에 최소값
        int min = Math.min(20, 30);

        // Math.random ( 0 <= 범위 < 1 랜덤)
        double random = Math.random();

        // Math.rint(값) 주어진 값에 가까운 정수
        double rint = Math.rint(5.3);

        // Math.round(값) - 반올림
        double round = Math.round(5.3);

        System.out.println("PI : " + PI);
        System.out.println("ceil1: " + ceil1);
        System.out.println("ceil2: " + ceil2);
        System.out.println("floor1: " + floor1);
        System.out.println("floor2: " + floor2);
        System.out.println("max: " + max);
        System.out.println("min: " + min);
        System.out.println("random: " + random);
        System.out.println("rint: " + rint);
        System.out.println("round: " + round);

    }
}

 

 

 

 

주사위 번호 뽑기

 

int num = (int) (Math.random() * 6) + 1

 

 

로또 번호 뽑기

 

int num = (int) (Math.random() * 45) + 1

 

 


 

 

Date 클래스

 

Date는 날짜를 표현하는 클래스이다. Date 클래스는 객체 간에 날짜 정보를 주고 받을 때 주로 사용한다.

 

Date now = new Date()

 

Date() 생성자만 주로 사용한다. Date() 생성자는 컴퓨터의 현재 날짜를 읽어 Date 객체로 만든다.

 

 

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateMain {
    public static void main(String[] args) {
        Date now = new Date();
        String String_now = now.toString();

        SimpleDateFormat SimpleDate = new SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
        String Simple_now = SimpleDate.format(now);

        System.out.println(String_now);
        System.out.println(Simple_now);
    }
}

 

 

 

 

Calendar 클래스

 

 

Calendar 클래스는 달력을 표현한 클래스이다.

Calendar 클래스는 추상(abstract) 클래스이므로 new 연산자를 사용해서 인스턴스를 생성할 수 없다.

 

그 이유는 날짜와 시간을 계산하는방법이 지역과 문화와 나라에 따라 다르기 때문이다.

 

기본적으로 getInstance() 메소드를 이용하면 현재 운영체제에 설정되어 있는 시간대(TimeZone)을 기준으로 한 Calendar 객체를 얻을 수 있다.

 

Calendar now = Calendar.getinstance();

 

import java.util.Calendar;

public class CalendarMain {
    public static void main(String[] args) {

        Calendar now = Calendar.getInstance();

        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH);
        int day = now.get(Calendar.DAY_OF_MONTH);

        int week = now.get(Calendar.DAY_OF_WEEK);

        String weekend = null;

        switch (week) {
            case Calendar.MONDAY:
                weekend = "월";
                break;
            case Calendar.TUESDAY:
                weekend = "화";
                break;
            case Calendar.WEDNESDAY:
                weekend = "수";
                break;
            case Calendar.THURSDAY:
                weekend = "목";
                break;
            case Calendar.FRIDAY:
                weekend = "금";
                break;
            case Calendar.SATURDAY:
                weekend = "토";
                break;
            default:
                weekend = "일";
        }

        int am_pm = now.get(Calendar.AM_PM);
        String now_AM_PM = null;
        if(am_pm == Calendar.AM) {
            now_AM_PM = "오전";
        } else {
            now_AM_PM = "오후";
        }

        int hour = now.get(Calendar.HOUR);
        int minute = now.get(Calendar.MINUTE);
        int seconds = now.get(Calendar.SECOND);

        System.out.println(year + "년 " + month + "월 " + day + "일");
        System.out.println(weekend + "요일 " + now_AM_PM);
        System.out.println(hour + "시 " + minute + "분 " + seconds + "초");

    }
}

 

 

 

Format 클래스

 

숫자형식을 위해 DecimalFormat, 날짜 형식을 위해 SimpleDateFormat, 매개변수화된 문자열 형식을 위해 MssageFormat이 있다.

 

import java.text.DecimalFormat;

public class DecimalFormatMain {

    public static void main(String[] args) {

        double number = 15000.25;

        DecimalFormat df = new DecimalFormat("0");
        System.out.println(df.format(number));
        

        df = new DecimalFormat("0.0");
        System.out.println(df.format(number));
        

        df = new DecimalFormat("000000000.00000");
        System.out.println(df.format(number));
        

        df = new DecimalFormat("#");
        System.out.println(df.format(number));
        

        df = new DecimalFormat("#.#");
        System.out.println(df.format(number));
        

        df = new DecimalFormat("#########,######");
        System.out.println(df.format(number));


        df = new DecimalFormat("#.0");
        System.out.println(df.format(number));


        df = new DecimalFormat("+#.0");
        System.out.println(df.format(number));


        df = new DecimalFormat("-#.0");
        System.out.println(df.format(number));


        df = new DecimalFormat("#,###.0");
        System.out.println(df.format(number));


        df = new DecimalFormat("0.0E0");
        System.out.println(df.format(number));


        df = new DecimalFormat("+#,### ; -#,###");
        System.out.println(df.format(number));


        df = new DecimalFormat("#.# %");
        System.out.println(df.format(number));


        df = new DecimalFormat("\u00A4 #,###");
        System.out.println(df.format(number));
    }

}

 

 

 

 

 

import java.text.SimpleDateFormat;
import java.util.Date;

public class SimpleDateFormatMain {
    public static void main(String[] args) {

        Date now = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(now));

        sdf = new SimpleDateFormat("yyyy년 MM월 dd일");
        System.out.println(sdf.format(now));

        sdf = new SimpleDateFormat("yyyy.MM.dd a HH:mm:ss");
        System.out.println(sdf.format(now));

        sdf = new SimpleDateFormat("오늘은 E요일");
        System.out.println(sdf.format(now));

        sdf = new SimpleDateFormat("올해의 D번쨰 날짜");
        System.out.println(sdf.format(now));

        sdf = new SimpleDateFormat("이달의 d번쨰 날");
        System.out.println(sdf.format(now));
    }
}

 

 

 

import java.text.MessageFormat;

public class MessageFormatMain {
    public static void main(String[] args) {

        String blog = "개발에만 집중";
        String blog_url = "https://focus-dev.tistory.com";

        String text = "블로그 이름 : {0} \n블로그 주소 : {1} ";
        String result = MessageFormat.format(text, blog, blog_url);
        System.out.println(result);


    }
}

 

 

 

 

java.time 패키지

 

 

자바 8 부터 날짜와 시간을 나타내는 여러가지 API가 추가되었다. Calendar를 사용하면 시간을 얻을 수 있지만 날짜를 조작하기에는 힘들었기때문이다.

 

import java.time.*;

public class DateTimeMain {
    public static void main(String[] args) throws InterruptedException {

        LocalDate currDate = LocalDate.now();
        System.out.println( "현재 날짜: " + currDate);
        LocalDate targetDate = LocalDate.of(2020, 5, 1);
        System.out.println( "목표 날짜: " + targetDate);

        LocalTime currTime = LocalTime.now();
        System.out.println( "현재 시간: " + currTime);
        LocalTime targetTime = LocalTime.of(6, 30, 0, 0);
        System.out.println( "목표 시간: " + targetTime);

        LocalDateTime currDateTime = LocalDateTime.now();
        System.out.println("현재 날짜와 시간: " + currDateTime);
        LocalDateTime targetDateTime = LocalDateTime.of(2020, 5, 1, 6, 30, 0, 0);
        System.out.println("목표 날짜와 시간: " + targetDateTime);


    }
}

 

 

import java.time.LocalDate;
import java.time.LocalDateTime;

public class DateTimeInfoMain {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);

        String DateTime = now.getYear() + "년 ";
        DateTime += now.getMonthValue() + "월 ";
        DateTime += now.getDayOfMonth() + "일 ";
        DateTime += now.getDayOfWeek() + " ";

        String DateTime2 = now.getHour() + "시 ";
        DateTime2 += now.getMinute() + "분 ";
        DateTime2 += now.getSecond() + "초 ";
        DateTime2 += now.getNano();

        System.out.println(DateTime);
        System.out.println(DateTime2);

        LocalDate nowDate = now.toLocalDate();
        if(nowDate.isLeapYear()) {
            System.out.println("윤년이 있습니다.");
        } else {
            System.out.println("윤년이 없습니다.");
        }


    }
}

 

 

빼기와 더하기

 

도트(.) 연산자로 연결해서 순차적으로 호출할 수 있다.

 

import java.time.LocalDateTime;

public class DateTimeOpMain {
    public static void main(String[] args ) {
        LocalDateTime now = LocalDateTime.now();

        System.out.println("현재시: " + now);

        LocalDateTime targetDateTime = now
                .plusYears(1)
                .minusMonths(3)
                .plusDays(10)
                .plusHours(4)
                .minusMinutes(5)
                .plusSeconds(10);

        System.out.println("조작 후 : " + targetDateTime);

    }
}

 

 

 

 

 

변경하기

 

with 메소드를 제외한 나머지는 메소드 이름만 보면 어떤 정보를 수정하는지 알 수 있다.

 

import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;

public class DateTimeChangeMain {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        System.out.println("현재 시간: " + now);

        LocalDateTime targetDateTime = null;

        targetDateTime = now
                .withYear(2020)
                .withMonth(5)
                .withDayOfMonth(1)
                .withHour(13)
                .withMinute(30)
                .withSecond(30);

        System.out.println("직접 변경: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.firstDayOfYear());
        System.out.println("이번 해의 첫 일: " + targetDateTime );

        targetDateTime = now.with(TemporalAdjusters.lastDayOfYear());
        System.out.println("이번 해의 마지막 일: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextYear());
        System.out.println("다음 해의 첫 일: " + targetDateTime);



        targetDateTime = now.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println("이번 달의 첫 일: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.lastDayOfMonth());
        System.out.println("이번 달의 마지막 일: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println("다음 달의 첫 일: " + targetDateTime);


        targetDateTime = now.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        System.out.println("이번 달의 첫 월요일: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        System.out.println("돌아오는 월요일: " + targetDateTime);

        targetDateTime = now.with(TemporalAdjusters.previous(DayOfWeek.MONDAY.MONDAY));
        System.out.println("지난 월요일: " + targetDateTime);

    }
}

 

 

 

날짜와 시간을 비교하기

 

 

날짜와 시간 클래스들은 다음과 같이 비교하거나 차이를 구하는 메소드들을 가지고 있다.

 

 

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class DateTimeCompareMain {
    public static void main(String[] args) {

        LocalDateTime startDateTime = LocalDateTime.of(2020, 1, 1, 0, 0, 0);
        System.out.println("시작일: " + startDateTime);

        LocalDateTime endDateTime = LocalDateTime.of(2020, 5, 5, 12, 30, 0);
        System.out.println("종료일: " + endDateTime);

        if(startDateTime.isBefore(endDateTime)) {
            System.out.println("진행 중입니다.");
        } else if(startDateTime.isEqual(endDateTime)) {
            System.out.println("종료합니다.");
        } else if(startDateTime.isAfter(endDateTime)) {
            System.out.println("종료했습니다.");
        }

        long remainYear = startDateTime.until(endDateTime, ChronoUnit.YEARS);
        long remainMonth = startDateTime.until(endDateTime, ChronoUnit.MONTHS);
        long remainDay = startDateTime.until(endDateTime, ChronoUnit.DAYS);
        long remainHour = startDateTime.until(endDateTime, ChronoUnit.HOURS);
        long remainMinute = startDateTime.until(endDateTime, ChronoUnit.MINUTES);
        long remainSecond = startDateTime.until(endDateTime, ChronoUnit.SECONDS);


        remainYear = ChronoUnit.YEARS.between(startDateTime, endDateTime);
        remainMonth = ChronoUnit.MONTHS.between(startDateTime, endDateTime);
        remainDay = ChronoUnit.DAYS.between(startDateTime, endDateTime);
        remainHour = ChronoUnit.HOURS.between(startDateTime, endDateTime);
        remainSecond = ChronoUnit.SECONDS.between(startDateTime, endDateTime);

        System.out.println("남은 해: " + remainYear);
        System.out.println("남은 달: " + remainMonth);
        System.out.println("남은 일: " + remainDay);
        System.out.println("남은 시간: " + remainHour);
        System.out.println("남은 분: " + remainMinute);
        System.out.println("남은 초: " + remainSecond);

        Period period = Period.between(startDateTime.toLocalDate(), endDateTime.toLocalDate());
        System.out.print("남은 기간: " + period.getYears() + "년");
        System.out.print(period.getMonths()+ "달");
        System.out.println(period.getDays() + "일 ");

        Duration duration =
                Duration.between(startDateTime.toLocalTime(), endDateTime.toLocalTime());

        System.out.println("초:" + duration.getSeconds());


    }
}

 

파싱, 포맷팅

날짜와 시간 클래스는 문자열을 파싱(parsing)해서 날짜와 시간을 생성하는 메소드와 이와 반대로 날짜와 시간을 포맷팅(Formatting)된 문자열로 변환하는 메소드를 제공하고 있다.

 

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateTimeParsingMain {
    public static void main(String[] args) {
        DateTimeFormatter formatter;
        LocalDate localDate;

        localDate = LocalDate.parse("2020-05-01");
        System.out.println(localDate);

        formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        localDate = LocalDate.parse("2020-05-01", formatter);
        System.out.println(localDate);

        formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        localDate = LocalDate.parse("2020/05/01", formatter);
        System.out.println(localDate);

        formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd");
        localDate = LocalDate.parse("2020.05.01", formatter);
        System.out.println(localDate);

    }
}

 

 

날짜와 시간을 포맷팅된 문자열로 변환시키는 format() 메소드이다.

 

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

public class DateTimeFormatMain {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter dateFormatter =
                DateTimeFormatter.ofPattern("yyyy년 M월 d일 a h시 m분");

        System.out.println(now.format(dateFormatter));
    }
}