IT/development

[java]์ƒ๋…„์›”์ผ๋กœ ๋งŒ๋‚˜์ด ๊ณ„์‚ฐ ์˜ˆ์ œ

์•Œ ์ˆ˜ ์—†๋Š” ์‚ฌ์šฉ์ž 2022. 11. 24.

๋ชฉ์ฐจ

    image source:https://unsplash.com/s/photos/java

     

    [java]์ƒ๋…„์›”์ผ๋กœ ๋งŒ๋‚˜์ด ๊ณ„์‚ฐ ์˜ˆ์ œ

    ์ƒ๋…„์›”์ผ๋กœ ๋งŒ๋‚˜์ด ๊ตฌํ•˜๋Š” ์˜ˆ์ œ ์†Œ์Šค์ด๋‹ค.

    	public static int getAgeByBirthday(String birthDay) {
        	// param๊ฐ’์€ "2000-01-01" ํƒ€์ž…์˜ ๋ฐ์ดํ„ฐ๋ผ๋Š” ๊ฐ€์ •
    		String birth = StrUtils.replace(birthDay, "-", "");
            // ๋…„,์›”,์ผ ์ž๋ฅด๊ธฐ
    		int birth_year = StrUtils.parseInt(StrUtils.substring(birth, 0, 4));
    		int birth_month = StrUtils.parseInt(StrUtils.substring(birth, 4, 6));
    		int birth_day = StrUtils.parseInt(StrUtils.substring(birth, 6, 8));
    		Calendar current = Calendar.getInstance();
            // ํ˜„์žฌ๋…„, ์›”, ์ผ get
    		int current_year = current.get(Calendar.YEAR);
    		int current_month = current.get(Calendar.MONTH) + 1;
    		int current_day = current.get(Calendar.DAY_OF_MONTH);
    		int age = current_Year - birth_Year;
            // ๋งŒ๋‚˜์ด
    		if (birth_month * 100 + birth_day > current_month * 100 + current_day) {
    			age--; 
    		}
    		return age;
    	}

    ๋Œ“๊ธ€