요일을 switch~case문 말고 배열로 할당하기
package calendar01;
import java.util.Calendar;
public class Calendar02 {
public static void main(String[] args) {
//배열로 요일 할당하기
String[] week = {"일","월","화","수","목","금","토"};
Calendar date1 = Calendar.getInstance();
System.out.println(date1.get(Calendar.DAY_OF_WEEK));
System.out.println(week[date1.get(Calendar.DAY_OF_WEEK)-1]);
}
}
=>
6
금
date1.set(2022, 6, 8); //년월일 내가 설정
System.out.println(date1.get(Calendar.YEAR) + "년");
date1.set(2021, 3, 20, 7, 20, 53); //년월일시분초 설정
System.out.println(date1.get(Calendar.HOUR) + "시");
//date.set(Calendar.MONTH, 11);
date1.set(Calendar.MONTH, Calendar.DECEMBER); //달은 0부터 시작이라 숫자로 넣으면 헷갈려서 보통 이름으로 넣음
System.out.println((date1.get(Calendar.MONTH)+1) + "월");
date1.set(Calendar.HOUR_OF_DAY, 15);
System.out.println(date1.get(Calendar.HOUR_OF_DAY) + "시(24시)");
=>
2022년
7시
12월
15시(24시)
package calendar01;
import java.util.Calendar;
public class Calendar03 {
public static void main(String[] args) {
Calendar date1 = Calendar.getInstance();
date1.set(2022,3,10);
System.out.println(date1.get(Calendar.YEAR) + "년 " + date1.get(Calendar.MONTH) + "월 " + date1.get(Calendar.DATE) + "일");
date1.add(Calendar.DATE, 100); //100일 후의 날짜, 전의 날짜를 구하고 싶으면 마이너스 넣기
System.out.println(date1.get(Calendar.YEAR) + "년 " + date1.get(Calendar.MONTH) + "월 " + date1.get(Calendar.DATE) + "일");
date1.add(Calendar.DATE, -100); //전의 날짜를 구하고 싶으면 마이너스 넣기
System.out.println(date1.get(Calendar.YEAR) + "년 " + date1.get(Calendar.MONTH) + "월 " + date1.get(Calendar.DATE) + "일");
//두 달 후
date1.add(Calendar.MONTH, 2);
System.out.println(date1.get(Calendar.YEAR) + "년 " + date1.get(Calendar.MONTH) + "월 " + date1.get(Calendar.DATE) + "일");
}
}
=>
2022년 3월 10일
2022년 6월 19일
2022년 3월 10일
2022년 5월 10일
-date객체
-★★★SimpleDateFormat :
날짜와 시간을 내가 설정한 형태로 출력할 수 있음
package calendar01;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Date04 {
public static void main(String[] args) {
Date now = new Date();
System.out.println(now.toString()); //이것보단 밑에 거 더 많이 사용
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm"); //월은 대문자
System.out.println(sdf.format(now));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//대문자 HH는 24시간 시. 잘 안 쓰고 위에 거에서 오전/오후 추가해서 씀
System.out.println(sdf2.format(now));
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd hh:mm a"); //a 오전오후 추가
System.out.println(sdf3.format(now));
SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(sdf4.format(now));
SimpleDateFormat sdf5 = new SimpleDateFormat("yy/M/d");
System.out.println(sdf5.format(now));
SimpleDateFormat sdf6 = new SimpleDateFormat("yy년 MM월 dd일 E요일"); //E 요일 추가
System.out.println(sdf6.format(now));
}
}
=>
Fri Mar 03 11:14:55 KST 2023
2023-03-03 11:14
2023-03-03 11:14
2023-03-03 11:14 오전
2023/03/03
23/3/3
23년 03월 03일 금요일
Date와 Calendar의 단점을 개선한 새로운 클래스 제공
이 패키지에 속한 모든 클래스들은 불변이다.
만들어졌지만 이거 잘 사용 안 한대... (대체 왜)
package calendar01;
import java.time.LocalDate;
public class LocalDate05 {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println(today); //toString 안 해도 값 가져올 수 있음
System.out.println(today.getYear() + "년");
System.out.println(today.getMonth());
System.out.println(today.getMonthValue() + "월"); //얘는 달에 대한 +1 안 해줘도 됨
System.out.println(today.getDayOfMonth() + "일");
System.out.println("365일 중, " + today.getDayOfYear() + "일째");
System.out.println(today.getDayOfWeek());
System.out.println(today.getDayOfWeek().getValue()); //요일을 숫자로 출력
System.out.println("이 달은 총 " + today.lengthOfMonth() + "일까지 입니다.");
System.out.println("올해는 총 " + today.lengthOfYear() + "일 입니다.");
System.out.println("올해는 윤년이 " + today.isLeapYear() + "입니다.");
LocalDate endDay = LocalDate.of(2023, 7, 20); //내가 날짜 설정
System.out.println(endDay);
}
}
=>
2023-03-03
2023년
MARCH
3월
3일
365일 중, 62일째
FRIDAY
5
이 달은 총 31일까지 입니다.
올해는 총 365일 입니다.
올해는 윤년이 false입니다.
2023-07-20
package calendar01;
import java.time.LocalTime;
public class LocalTime06 {
public static void main(String[] args) {
LocalTime time = LocalTime.now();
System.out.println(time);
System.out.println(time.getHour() + "시");
System.out.println(time.getMinute() + "분");
System.out.println(time.getSecond() + "초");
LocalTime endTime = LocalTime.of(18, 20, 01);
System.out.println(endTime);
}
}
=>
12:03:07.491630900
12시
3분
7초
18:20:01
package calendar01;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
public class LocalDateTime07 {
public static void main(String[] args) {
LocalDateTime today = LocalDateTime.now();
System.out.println(today);
LocalDateTime startDT = LocalDateTime.of(2023, 02, 8, 9, 30, 01);
LocalDateTime endDT = LocalDateTime.of(2023, 07, 20, 18, 20, 30);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd a hh:mm:ss");
//여기선 별도의 클래스와 ofpattern 키워드로 형식 설정
System.out.println("시작일: " + startDT.format(dtf));
System.out.println("종료일: " + endDT.format(dtf));
if(today.isBefore(endDT)) {
System.out.println("진행 중입니다.");
} else if (today.isEqual(endDT)) { // isEqual 대신에 equals 사용해도 됨
System.out.println("종료합니다.");
}else if(today.isAfter(endDT)) {
System.out.println("종료했습니다.");
}
// 날짜만 가능(시간 안 됨)
LocalDate today2 = LocalDate.now();
LocalDate endToday = LocalDate.of(2023,07,20);
Period period = today2.until(endToday);
System.out.print(period.getMonths() + "개월 " + period.getDays() + "일 남았습니다.");
System.out.println();
//날짜 시간 모두 가능
LocalTime endTime = LocalTime.of(18, 20, 30);
LocalTime now = LocalTime.now();
System.out.println(now.until(endTime, ChronoUnit.HOURS) + "시간 남았습니다.");
System.out.println(today.until(endDT, ChronoUnit.HOURS) + "시간 남았습니다.");
System.out.println(today.until(endDT, ChronoUnit.MONTHS) + "개월 남았습니다.");
System.out.println(today.until(endDT, ChronoUnit.DAYS) + "일 남았습니다.");
//시간만 가능
Duration duration = Duration.between(now, endTime);
System.out.println(duration.getSeconds() + "초 남았습니다.");
// 나누기 60 하면 분, 또 나누기 60하면 시가 됨.
//날짜 시간 모두 가능
System.out.println(today.plusYears(1).format(dtf)); //오늘 날짜 시간으로부터 1년 후
System.out.println(today.plusMonths(3).format(dtf)); //오늘 날짜 시간으로부터 3개월 후
System.out.println(today.plusDays(15).format(dtf)); //오늘 날짜 시간으로부터 15일 후
System.out.println("---------------------------");
System.out.println(today.minusYears(1).format(dtf)); //오늘 날짜 시간으로부터 1년 전
System.out.println(today.minusMonths(3).format(dtf)); //오늘 날짜 시간으로부터 3개월 전
System.out.println(today.minusDays(15).format(dtf)); //오늘 날짜 시간으로부터 15일 전
}
}
=>
2023-03-03T12:17:05.397956900
시작일: 2023-02-08 오전 09:30:01
종료일: 2023-07-20 오후 06:20:30
진행 중입니다.
4개월 17일 남았습니다.
4시간 남았습니다.
3340시간 남았습니다.
4개월 남았습니다.
139일 남았습니다.
15685초 남았습니다.
2024-03-03 오후 02:06:15
2023-06-03 오후 02:06:15
2023-03-18 오후 02:06:15
---------------------------
2022-03-03 오후 02:06:15
2022-12-03 오후 02:06:15
2023-02-16 오후 02:06:15
시간대와 관련된 클래스들 제공
다시 말해, 국가별로 다른 시간대로 설정 가능
package calendar01;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Zoned08 {
public static void main(String[] args) {
ZonedDateTime seoulDT = ZonedDateTime.now(ZoneId.of("Asia/Seoul"));
System.out.println(seoulDT);
ZonedDateTime londonDT = ZonedDateTime.now(ZoneId.of("Europe/London"));
System.out.println(londonDT);
ZonedDateTime BerlinDT = ZonedDateTime.now(ZoneId.of("Europe/Berlin"));
System.out.println(BerlinDT);
//기준 시간
ZonedDateTime utc = ZonedDateTime.now(ZoneId.of("UTC"));
System.out.println(utc);
ZoneOffset seoulOffset = ZoneOffset.of("+09:00");
System.out.println(ZonedDateTime.now(seoulOffset));
// Calendar 사용 시 이전 버전에서의 활용. 이게 더 많이 쓴대....
TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");
Calendar now = Calendar.getInstance(timezone);
System.out.println(now.get(Calendar.HOUR) + "시");
}
}
=>
2023-03-03T14:20:10.862395100+09:00[Asia/Seoul]
//utc와의 차이가 +9시간
2023-03-03T05:20:10.864389900Z[Europe/London]
2023-03-03T06:20:10.876357900+01:00[Europe/Berlin]
2023-03-03T05:36:33.273629500Z[UTC]
2023-03-03T14:40:01.030401800+09:00
9시
여태까지 했던 것 복습~
package test02;
// getter, setter 변수만 있는 api를 "자바 빈" 이라고 말함 + 생성자 추가 + toString(오버라이딩)
public class Student {
private String stuNo;
private String name;
private int score; //자료형이 일정하지 않아서 배열 못 만듦-> 객체 만들어 객체를 배열로 넣음
private String address;
private String tel;
private boolean attending; //재학중인지 아닌지
//생성자 넣기!
Student() {
//메인에서 객체 생성시에 아무것도 안 넣을 수도 있어서 빈칸
}
//메인에서 객체 생성시에 모든 필드를 다 넣을 수도 있으니 source - constructor using Field로 체크하고 넣어줌
public Student(String stuNo, String name, int score, String address, String tel, boolean attending) {
//super(); 안 불러도 됨. 매개변수를 부모 클래스로 넘겨주지 않아도 되기 때문에 없어도 됨(상속이 없으니까)
this.stuNo = stuNo;
this.name = name;
this.score = score;
this.address = address;
this.tel = tel;
this.attending = attending;
}
//private형이라 가져올 수 없어서 source에서 get,set 설정으로 변수명 넣고 호출함
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public boolean isAttending() {
return attending;
}
public void setAttending(boolean attending) {
this.attending = attending;
}
//// toString 오버라이딩 source - Generate to String해서 보통 필드값만 체크해서 넣어주면 됨
@Override
public String toString() {
return "Student [stuNo=" + stuNo + ", name=" + name + ", score=" + score + ", address=" + address + ", tel="
+ tel + ", attending=" + attending + "]";
}
}
package test02;
public class FusionData {
//라이브러리는 바로 배열생성 못해서 필드로 넣어주든가 메소드로 만들든가 해야됨
void stuAdd(){ //메소드로 만듦
Student[] fusionStudent = new Student[2];
//융합 반의 학생은 2명,다같은 Student 타입이기 때문에 배열 만들기 가능
fusionStudent[0] = new Student("20230001","홍길동",98,"서울특별시","010-1234-5678",true);
fusionStudent[1] = new Student("20230001","아무개",56,"서울특별시","010-1111-2222",false);
for(int i=0; i<fusionStudent.length; i++) {
Student stu = fusionStudent[i]; //객체를 배열에 넣어주겠다! 하면 배열의 타입과 함께 이렇게
//System.out.println(stu); => 오버라이딩한 toString 값이 출력됨
System.out.println(stu.getName()+"\t"+stu.getScore()+"\t"+stu.isAttending());
//내가 원하는 것만 가져와 따로 출력하고 싶을 때 / "\t"는 탭만큼 띄어쓰기하는 것
}
/*
System.out.println(fusionStudent[0].getStuNo());
System.out.println(fusionStudent[0].getName()); //하나하나 내가 다 수동으로 가져오겠다하면 get
System.out.println(fusionStudent[0].toString()); //toString설정값으로 하겠다 하면 toString
System.out.println(fusionStudent[1]); //toString 안 써도 오버라이딩한 값 나옴
*/
}
}
package test02;
public class StudentTest {
public static void main(String[] args) {
FusionData fd = new FusionData();
fd.stuAdd();
}
}
평가는 public class FusionData를 잘 봐야함!!!! 메인이나 자바 빈 클래스는 수정할 필요 없음
더 세부설명!!!!
package test02;
class Person {
private String name;
private int age;
Person(){ }
Person(String name, int age) {
this.name = name;
this.age = age; //매개변수를 인스턴스 변수에 넣는 작업
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getage() {
return age;
}
@Override
public String toString() {
return "이름 : " + name + ", 나이 : " +age;
}
}
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person("홍길동",25);
//System.out.println(p2.name); private으로 만들어놔서 다른 클래스에서 접근 불가 그래서 get씀
System.out.println(p2.getName()); //api에서 get메서드 만들어주고 메인에서 get으로 출력
//p1.name = "아무개" private으로 만들어놔서 다른 클래스에서 수정 불가 그래서 set씀
p1.setName("아무개"); //api에서 set메서드 만들어주고 메인에서 set으로 호출
System.out.println("이름: " + p2.getName() + ", 나이: " + p2.getage());
//이렇게 원하는 형식을 출력하고 싶어서 출력문을 쓰다보면 사람이 100명이면 100개를 다 써야함 그래서 toString오버라이딩 필요
System.out.println(p1);
System.out.println(p2); //변수값만 출력해도 원하는 형식의 값이 출력!
}
}
DecimalFormat(숫자의 형식화):
숫자를 다양한 형식으로 출력할 수 있게 해주는 클래스.
잘 안 씀~
DecimalFotmat df = new DecimalFormat("#,###.##");
Number num = df.parse("1,234,567.89");