Calendar 객체 사용법(+n일전 구하기, 계산하기)

김희주·2023년 1월 19일
0

자잘한 Tip

목록 보기
1/8
post-thumbnail

1. cal.getTime();

	@RequestMapping(value="/dashboard", method = RequestMethod.GET)
    public String dashboard(ModelMap model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		
		
    	Calendar cal = Calendar.getInstance();						//현재 시간 정보 or 캘린더 객체 추출 
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");		//날짜 포맷 지정
    	String today = sdf.format(cal.getTime());					//현재 시간을 지정한 날짜 포맷으로 출력
    	
    	cal.add(Calendar.DATE, -6);
    	String today3dayBefore = sdf.format(cal.getTime());

    	List<DashBoard> totalCntMonth = notiSendTbRepository.totalCntMonth();
    	List<DashBoard> totalCntToday = notiSendTbRepository.totalCntToday();
    	
    	long tokenCnt  = clientDataTbRepository.countByUseYn(true);
    	
    	model.addAttribute("monthCnt", totalCntMonth.get(0));
    	model.addAttribute("todayCnt", totalCntToday.get(0));
    	model.addAttribute("today", today);
    	model.addAttribute("today3dayBefore", today3dayBefore);
    	model.addAttribute("tokenCnt", tokenCnt);
    	
    	model.addAttribute("username", session.getAttribute("name"));
		return "dashboard";

❓왜

String today = sdf.format(cal);

으로 안하고

String today = sdf.format(cal.getTime());

으로 할까?

System.out.println(cal);

으로 cal객체 자체를 찍으면
java.util.GregorianCalendar[time=1674086739163,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Seoul",offset=32400000,dstSavings=0,useDaylight=false,transitions=22,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2023,MONTH=0,WEEK_OF_YEAR=3,WEEK_OF_MONTH=3,DAY_OF_MONTH=19,DAY_OF_YEAR=19,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=9,HOUR_OF_DAY=9,MINUTE=5,SECOND=39,MILLISECOND=163,ZONE_OFFSET=32400000,DST_OFFSET=0]
으로 뜨는데, 여기서 날짜 시간 부분만 추출해야 지정한 String 포맷으로 변환할 수 있다.

2. cal.add( , );

cal.add(Calendar.DATE, -6);	

cal에서 6일을 뺀다.
calendar 날짜 연산 참고

profile
백엔드 개발자입니다 ☘

0개의 댓글