본문 바로가기
Android Project/Extras..

[Android/Kotlin] 나이 계산앱

by juwon2 2023. 12. 10.

태어난 날짜를 선택하면 다양한 형태로 나이를 계산해주는 앱을 만들어봤다

 

생일을 입력하면 나의 나이와 분,시간,일,개월이 얼마나 경과했는지 보여주는 앱을 만들어봤다

 

시간들은 밀리초 기준으로 이렇게 표현했다

1초 = 1000밀리초 이기 때문에
1분 = 60초 = 1000*60 
1시간 = 1000*60*60 
1일 = 1시간*24 = 1000*60*60*24 
30일(한달) = 1일*30 = 1000*60*60*24*30 
나이 =>  1년 = 1달*12 = 1000*60*60*24*30*12

 

 

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:background="@color/backgroundColor"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="다양한 방법으로 내 나이를 계산해봐요!"
        android:textColor="@color/textColor"
        android:textSize="20sp"
        android:textStyle="bold"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="나이 계산기"
        android:padding="10dp"
        android:background="@color/primaryColor"
        android:textColor="@color/white"
        android:textSize="25sp"
        android:textStyle="bold"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="45dp"
        android:text="선택한 날짜"
        android:textColor="@color/lightGreyTextColor"
        android:textSize="18sp"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/tvSelectedDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:text="0000/00/00"
        android:textColor="@color/textColor"
        android:textSize="25sp"
        android:textStyle="bold"/>

    <Button
        android:id="@+id/btnDateSelect"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:backgroundTint="#FFFFFF"
        android:textColor="#929292"
        android:text="날짜 선택하기"
        android:layout_marginTop="20dp"
        android:textStyle="bold"
        android:textSize="20sp"
        android:elevation="10dp"
        android:layout_marginLeft="30dp"
        android:layout_marginRight="30dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal">

        <TextView
            android:id="@+id/tvYear"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="0"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="살"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal"
        android:layout_marginTop="10dp">

        <TextView
            android:id="@+id/tvAgeInMinutes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="0"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="분 경과"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>





    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal">

        <TextView
            android:id="@+id/tvClock"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="0"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="시간 경과"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal">

        <TextView
            android:id="@+id/tvDay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="0"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="일 경과"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>




    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal">

        <TextView
            android:id="@+id/tvMonth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="0"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:text="개월 경과"
            android:textColor="@color/textColor"
            android:textSize="30sp"
            android:textStyle="bold" />
    </LinearLayout>



</LinearLayout>

activity_main.xml

 

 

class MainActivity : AppCompatActivity() {


    // 변수선언
    private var tvSelectedDate : TextView? = null
    private var tvAgeInMinutes : TextView? = null
    private var tvClock : TextView? = null
    private var tvMonth : TextView? = null
    private var tvDay : TextView? = null
    private var tvYear : TextView? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        // btn이라는 변수 초기화(레이아웃에서 텍스트 뷰의 id를 가져옴)
        val btn : Button = findViewById(R.id.btnDateSelect)

        // tvSelectedDate이라는 변수 초기화
        tvSelectedDate = findViewById(R.id.tvSelectedDate)

        // tvAgeInMinute변수 초기화
        tvAgeInMinutes = findViewById(R.id.tvAgeInMinutes)

        //tvClock변수 초기화
        tvClock = findViewById(R.id.tvClock)

        //tvMonth변수 초기화
        tvMonth = findViewById(R.id.tvMonth)

        //tvDay변수 초기화
        tvDay = findViewById(R.id.tvDay)

        //tvYear변수 초기화
        tvYear = findViewById(R.id.tvYear)




        // btnDateSelect(버튼) 눌렀을때
        btn.setOnClickListener {

            clickDateSelect()   // clickDateSelect 함수안에 있는 내용이 실행
        }

    }



    // clickDatePicker함수
    private fun clickDateSelect(){

        val myCalendar = Calendar.getInstance()     //캘린더를 불러옴
        val year = myCalendar.get(Calendar.YEAR)    //현재 년도
        val month = myCalendar.get(Calendar.MONTH)  //현재 월 (1월:0 ,12월:11)
        val day = myCalendar.get(Calendar.DAY_OF_MONTH) // 현재 날짜(일)

        //달력 다이어로그
        val dpd =
            // DatePickerDialog사용해서 캘린더 다이얼로그 띄우기
            DatePickerDialog(this,
                // DatePickerDialog 눌렀을때 (전달할 매개변수(view는 여기서 쓰진않음(_로도 표현가능))
                // 년,월,일 매개변수 전달
                DatePickerDialog.OnDateSetListener { view, selectedyear, selectedmonth, selecteddayofMonth ->

                //month +1은 month를 0~11까지로 값을 읽기 때문에 +1을 해줘야 1~12월로 할 수 있다.
                Toast.makeText(this, "${selectedyear}년 ${selectedmonth + 1}월 ${selecteddayofMonth}일", Toast.LENGTH_SHORT).show()

                    //tvSelectedDate의 id를 가진 Text 부분을 내가 선택한 날짜로 바꿔주는 코드
                val selectedDate = "$selectedyear/${selectedmonth + 1}/$selecteddayofMonth"
                    //setText(text)를 이용해서 selectedDate의 결괏값을 텍스트뷰에 표현 (null형식이라서 ?씀)
                tvSelectedDate?.text = selectedDate.toString()

                    // 날짜 형식설정(SimpleDateFormat을 활용해 theDate변수를 만든다음)
                val sdf = SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)
                    val theDate = sdf.parse(selectedDate)   //그걸 theDate변수에 전달 //parse는 Date형태로 바꿔줌



                    // 선택한 날짜(분)    //1분 = 60초 = 1000*60
                    // 달력에서 선택한 날짜 담은변수 theDate 만들기
                    //여기서 Date 개체의 시간(밀리초)가 표시된다
                    //그리고 우리가 알고 있듯이 밀리초라는 공식은 1000으로 나누면 초로 변환될 수 있다
                    //그리고 초를 60으로 나누어 분으로 변환할 수 있다
                    //이제 선택한 날짜를 분 단위로 변경
                    // null안정성을 위해 let안에 코드써준다
                    //그리고 time과 getTime은 같은 기능이다.
                theDate?.let {
                    val selectedDateInMinutes = theDate.time /1000/60

                    // 여기서는 위에서 사용한 날짜 형식을 사용하여 현재 날짜를 분석했다.
                    // selectedDateInMinutes으로 선택한 날짜에서 현재까지 얼마나 시간이 지났는지 초단위로
                    // format을 통해 1970년 1월1일부터 "현재시각"을 초단위로 알수있음
                    val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))


                    currentDate?.let {
                        // 현재 날짜(분)
                        // 지금까지 지난시간을 분단위로(선택한날짜와 현재날짜 사이 지난시간을 분단위로)
                        val currentDateInMinutes = currentDate.time /1000/60

                        //select는 1970년 1월 1일 자정부터 태어날 날 자정까지의 시간
                        //current는 1970년 1월 1일 자정부터 오늘 날까지의 시간
                        //이제 몇 분 안에 차이를 확인하겠다.
                        //현재 Minutes에서 선택한 Minutes를 뺀다.
                        //현재 Minutes에서 선택한 Minutes를 빼야지 두 날짜사이의 분을 정확히 알수있다
                        val differenceInMinutes = currentDateInMinutes - selectedDateInMinutes


                        // differenceInMinutes의 결괏값을 텍스트뷰에 표현 (tvAgeInMinutes자리)
                        tvAgeInMinutes?.text = differenceInMinutes.toString()




                        //몇살인지(나이)
                        //1년 = 1달*12 = 1000*60*60*24*30*12
                        theDate?.let {

                            val selectClock = theDate.time /1000/60/60/24/30/12
                            val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                            currentDate?.let {
                                val currenClock = currentDate.time /1000/60/60/24/30/12

                                val differenceInClock = currenClock-selectClock
                                tvYear?.text = differenceInClock.toString()

                            }
                        }



                        //시간
                        //1시간 = 1000*60*60
                        theDate?.let {

                            val selectClock = theDate.time /1000/60/60
                            val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                            currentDate?.let {
                                val currenClock = currentDate.time /1000/60/60

                                val differenceInClock = currenClock-selectClock
                                tvClock?.text = differenceInClock.toString()

                            }
                        }



                        //일
                        //1일 = 1시간*24 = 1000*60*60*24
                        theDate?.let {

                            val selectClock = theDate.time /1000/60/60/24
                            val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                            currentDate?.let {
                                val currenClock = currentDate.time /1000/60/60/24

                                val differenceInClock = currenClock-selectClock
                                tvDay?.text = differenceInClock.toString()

                            }
                        }



                        //개월
                        //30일(한달) = 1일*30 = 1000*60*60*24*30
                        theDate?.let {

                            val selectMonth = theDate.time /1000/60/60/24/30
                            val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))

                            currentDate?.let {
                                val currenClock = currentDate.time /1000/60/60/24/30

                                val differenceInClock = currenClock-selectMonth
                                tvMonth?.text = differenceInClock.toString()

                            }
                        }




                    }
                }

            }, year, month, day )



        //달력에서 날짜 선택을 전날까지만 가능하게 제한(오늘과 미래날짜 선택못하게)
        //86400000은 하루의 ms 값이다.
        //datepicker속성을 특정날짜(전날)까지만 선택할수있게 maxDate대입 (한시간 360만 밀리초*24 =8640만 밀리초)
        dpd.datePicker.maxDate = System.currentTimeMillis() - 86400000

        dpd.show()
    }
}

MainActivity.kt

 

 

 

 

 

최종적인 앱 화면이다!

날짜 선택하기 버튼을 클릭하면 DatePickerDialog창이 나오면서 년도와 일을 선택할수있다.

결과화면은 내가 선택한 날짜가 뜨고 선택한 날짜를 기준으로 나이,분,시간,일,개월의 경과수를 계산해서 보여주는것을 확인할수있다.