Java.Util 패키지
- 날자 정보를 제공하는 유용한 api가 포함됨
- 기본 패키지에서 사용하려면 import 필요함
- import 단축 입력: 컨트롤 + 쉬프트 + O
메소드
- set() 메소드 : 시간 데이터를 내가 원하는 값으로 변경
- get() 메소드 : 필요한 상수 필드를 호출하여 저장된 년, 월, 일, 시, 분, 초 데이터를 가져옴
- format() 메소드 : date 타입만 이용 가능(다른 타입은 date로 변환해서 대입)
- getTimeInMillins() : 롱 타입으로 시간 데이터를 변경해주는 메소드
-> new Date에 넣고 사용하면 해당일의 밀리세컨을 알수 있음 - .of() : static 타입으로 내가 원하는 날짜로 설정 가능
- .now(): static 타입으로 현재 날짜 데이터를 불러옴
- add(넣을 날자 데이터, 넣을 int 값) : 날자 데이터를 입력값만큼 바꿔줌
System.out.println(new Date(gc.getTimeInMillis()));
GregorianCalendar t = new GregorianCalendar();
GregorianCalendar b = new GregorianCalendar(1993,11-1,9);
// System.out.println(t-b);
// 객체끼리 연산 불가
System.out.println((t.getTimeInMillis() - b.getTimeInMillis())/1000 + "s");
System.out.println((t.getTimeInMillis() - b.getTimeInMillis())/6000 + "m");
System.out.println((t.getTimeInMillis() - b.getTimeInMillis())/36000 + "h");
System.out.println((t.getTimeInMillis() - b.getTimeInMillis())/(36000*24) + "days");
//1000으로 나누면 초, 6000나누면 분, 36000나누면 시, 24를 곱해주면 일 기준일부터 특정일까지의 기간을 알 수 있다.
//of()
ld = LocalDate.of(1999, 11, 8);
➕ java.sql.Date → JDBC 연동해서 쓸 때 사용함 : DB 관련 날짜
[요즘추세]
java.time.LocalDateTime
java.time.LocalDate
java.time.LocalTime
1. Date 클래스
- 날자 표현 클래스
- 실행하는 컴퓨터에 설정된 날짜를 가져옴
- 기본 출발값(0)은 국제표준시각 기준 1970년 1월 1일 00: 00이다.
- 생성자 몇 개만 타입으로 사용 가능하고 나머지는 모두 deprecated(사라질예정이라는 뜻)
- Calendar or GregorianCalendar 클래스 사용 권장
- java.util.date 안에 date() 메소드가 있다.
- 객체 간 날짜 정보 주고받을 때 매개 변수나 리턴 타입으로 주로 사용됨
- void method(Date date) {…}
- Date method() {…}
- 클래스이기도 하기 때문에 스스로 객체 생성도 가능
- 객체 간 날짜 정보 주고받을 때 매개 변수나 리턴 타입으로 주로 사용됨
Date now = new Date(); //오늘 날짜 데이터를 저장함
System.out.println(now);
//Wed Mar 06 17:19:11 KST 2024 출력
today = new Date(1234567890000L); //매개변수 롱타입도 가능
System.out.println(today);
//Sat Feb 14 08:31:30 KST 2009
- 기본 출력 형식: Sat Feb 14 08:31:30 KST 2009
⇒ 원하는 형식을 얻기 위해서 java.text 패키지의 SimpleDateFormat 클래스 및 format()메소드와 함께 사용됨
SimpleDateFormat sdf = neew SimpleDateFormat("yyyy년 MM월 dd일 hh시 mm분 ss초");
String strNow = sdf.format(now);
2. Calendar 클래스
- 달력을 표현한 클래스 ⇒ 운영체의 날짜 및 시간 기준으로 다양한 정보를 얻을 수 있음
- 추상 클래스 = new 연산자로 인스턴스 생성 불가
- 생성자가 protected이기 때문
⇒ 캘린더를 가져오는 getInstance() 메소드를 통해 이용해야 한다. (꼭 뒤에 붙여줘야함) Calendar now = Calendar.getInstance();
- 원하는 날자를 세팅하려면 set() 메소드를 통해 가능하다
- 생성자가 protected이기 때문
Calendar birth = Calendar.getInstance();
birth.set(Calendar.YEAR, 1996);
birth.set(Calendar.MONTH, 10-1);
birth.set(Calendar.DATE, 28);
birth.set(Calendar.HOUR, 7);
birth.set(Calendar.MINUTE, 30);
birth.set(Calendar.SECOND, sec);
- 출력도 바로 하면 안됨 → System.out.println(jh); ⇒ 외계어
- 변수로 저장해서 변수를 묶어서 출력
year = birth.get(Calendar.YEAR);
month = birth.get(Calendar.MONDAY);
date = birth.get(Calendar.DATE);
hour = birth.get(Calendar.HOUR);
min = birth.get(Calendar.MINUTE);
System.out.println("탄신일 : " + year + ". " + month + ". " + date + "." + hour + ".");
- Calendar 클래스 내에는 아래와 같이 다양한 상수가 있음
- 🚨 주의: month 호출시 항상 +1 필요
int year = now.get(Calendar.YEAR);
int year = now.get(Calendar.MONTH) + 1; //월을 리턴, 1~12므로 1을 더해줘야함
int year = now.get(Calendar.DAY_OF_MONTH); //일 리턴
int year = now.get(Calendar.DAY_OF_WEEK); //요일 리턴, 1~7 숫자로 나옴
int year = now.get(Calendar.AM_PM);
int year = now.get(Calendar.HOUR);
int year = now.get(Calendar.MINUTE);
int year = now.get(Calendar.SECOND);
3. GregorianCalendar 클래스 (int)
Calendar 클래스의 후손 클래스, date type
- 년, 월, 일, 시, 분, 초 정보를 필드를 통해 다룰 수 있음
- new 연산자 사용 가능
- 매개변수 있는 생성자로 원하는 날자 지정 가능
gc = new GregorianCalendar(2001,4,21);
- get을 통한 생성 방법도 calendar와 동일하게 활용 가능
- 출력도 calendar와 마찬가지로 변수로 저장해서 변수를 모아서 진행해야함
minusMonths() ….() → 해당 날짜 데이터에서 특정값을 빼줌
DayofWeek 클래스의 getDayOfWeek()
4. SimpleDateFormat클래스 → 날짜 원하는 형태 지정하기
java.text 소속의 클래스로 원하는 문자열형태로 지정할 수 있다.
- new 연산자 이용 가능
- SimpleDateFormat(”형식문자열”)
- y M d h m s e(요일)
- web 날짜값은 yyyy-MM-dd가 기본 형태이다.
- 주의 : Date 객체만 이용 가능, 즉 Gregorian은 이용 불가능
제공 메소드:
- .format(포맷) : 해당 포맷에 맞는 날짜로 리턴
- date type만 이용 가능
- 다른 타입은 date로 변환해서 대입
- parse() : 날짜형식인지 체크해줌
//java.text.SimpleDateFormat클래스
//형식 지정
SimpleDateFormat sdf = new SimpleDateFormat("yyyy년 MM월 dd일");
String strToday = sdf.format(today); //해당 포맷에 맞는 날자를 리턴해줌
System.out.println(strToday);
GregorianCalendar gc = new GregorianCalendar();
//format 메소드는 datetype만 이용가능, 다른 타입은 date로 변환해서 대입
//GregorianCalender -> Date 로 변환해서 format 이용하기
Date jBirth = new Date(gc.getTimeInMillis()); //날자에 대한 롱 타임 가져오는 밀리스
strToday = sdf.format(jBirth);
System.out.println(strToday);
5. java.util.stream 클래스 (stream API)
stream 클래스의 모든 메소드는 stream type을 반환하도록 되어있다.
복사해서 데이터를 읽어오기 때문에 하나의 stream에는 하나만 이용가능하다.
1) 메소드
- filter() : 매개변수 안에 선별할 조건 및 선별 함수를 작성해서 원하는 데이터를 골라낼 수 있다.
- sorted(): 정렬시 사용
System.out.println("부산 사는 학생 나이 오름차순 정렬 : ");
result =
StudentDao.getStudent().stream().filter(s1 -> s1.getAddress().contains("부산"))
.sorted((pre, next) -> pre.getAge() - pre.getAge()).toList(); +면 이동
result.forEach(System.out::println);
- limit(): 갯수만큼만 진행하도록 해주는 메소드
System.out.println("나이가 가장 많은 경기도 거주 학생 5명 조회 : ");
student.stream().sorted((s1, s2) -> s2.getAge() - s1.getAge())
.limit(5)
.filter(s1 -> s1.getAddress().contains("경기도"))
.forEach(System.out::println);
- count(): 갯수 세어줌
System.out.println("경기도 사는 학생의 수를 구하기");
long count = student.stream()
.filter(stu -> stu.getAddress().contains("경기"))
.count();
System.out.println(count + "명");
- allMatch(매개변수 → 조건식) : 해당 변수의 데이터 중에서 조건을 모두 일치하면 true
anyMatch(매개변수 → 조건식): 하나라도 조건이 맞는 사람이 있으면 true
//allMatch
if (student.stream().allMatch(s1 -> s1.getName().contains("test"))){
System.out.println("모든 학생 이름에는 test가 포함되어 있다.");
} //1명이라도 안맞으면 출력안됨
//anyMatch
//100명 모두가 19살이 아니라서 나오지 않음
if(student.stream().allMatch(s1 -> s1.getAge() == 19) ) {
System.out.println("19살 학생이 있다.");
}
- takeWhile() : 첫 번째 false가 나오는 값까지만 집계하여 출력
- filter()는 회전을 모두 돌고 나서 출력한다는 점에서 차이가 있다.
List<Integer> data = List.of(10,20,30,40,50,60,70,80,90);
data.stream().takeWhile(i -> i <= 40)
.forEach(System.out::println);
- dropWhile(): 조건의 첫번째 false가 나온 다음값들만 집계하여 출력
List<Integer> data = List.of(10,20,30,40,50,60,70,80,90);
data.stream().dropWhile(i -> i <= 40)
.forEach(System.out::println);
- skip(): 해당 int 수만큼 건너뛴다.
//skip(x): 원하는 int수 만큼 건너뛰기
System.out.println("skip : ");
data.stream().skip(3).takeWhile(i -> i <= 70)
.forEach(System.out::println);
- map() : 반환되는 데이터로 완전 새로운 데이터를 만들어내는 기능 (매핑)
//전체 100명의 데이터였는데, map을 지나면서 이름만 있는 데이터로 출력해줌
student.stream().map(s1 -> "<h3>" + s1.getName() + "</h3>").forEach(System.out::println);
//새로운 객체 100개 만든 데이터를 만들어서 리스트에 저장함
List<Person> persons = student.stream() //stream API로 순회
.map(s1 -> new Person(s1.getName(), s1.getAge())) //이름과 나이로 퍼슨 객체 생성
.toList(); //이름과 나이만 리스트에 저장
.forEach(System.out::println); //메소드 참조로 출력
반응형
'JAVA' 카테고리의 다른 글
17. 자바(java) : java.time 패키지 클래스 정리(+ String 데이터로 날짜 활용하는 방법) (0) | 2024.04.24 |
---|---|
16. 자바(java) : java.lang 패키지 클래스 정리(Object, System, Class, String, Wrapper, Math) (0) | 2024.04.24 |
14-2. 자바(java) : 컬렉션(Collection) - Set, Map 개념과 활용 정리 (0) | 2024.04.24 |
14-1. 자바(java) : 컬렉션(Collection) - List 개념과 활용 정리 (0) | 2024.04.09 |
13. 자바(java) : 문자열 및 파일 입출력(IO)을 위한 스트림(stream) 간단 정리 (0) | 2024.04.09 |