코틀린 날짜 계산, 시간 (분을 초로) 변환

2022. 6. 7. 17:37카테고리 없음

*코틀린 파일 (메인)

1. 달력에서 선택한 날짜 담은 변수 theDate 만들기

   DatePickerDialog(this, { _, selectedYear, selectedMonth, selectedDayOfMonth ->
                Toast.makeText(
                    this,
                    "Input year is $selectedYear, month is ${selectedMonth + 1}, day is $selectedDayOfMonth",
                    Toast.LENGTH_LONG
                ).show()

                val selectedDate = "$selectedYear.${selectedMonth + 1}.$selectedDayOfMonth"
                tvSelectedDate?.text = selectedDate
                val sdf = SimpleDateFormat ("yyyy/MM/dd", Locale.ENGLISH)
                val theDate = sdf.parse(selectedDate)
            }
            ).show()

parent : date picker dialog . show() 

chidl : toast, selectedate.text, simple date format

 

date picker dialog >> https://developer.android.com/guide/topics/ui/controls/pickers?hl=ko 

 

선택 도구  |  Android 개발자  |  Android Developers

선택 도구 Android에서 제공하는 컨트롤로 사용자는 시간이나 날짜를 바로 사용 가능한 대화상자로 선택할 수 있습니다. 각 선택 도구는 시간(시, 분, 오전/오후)이나 날짜(년, 월, 일)의 각 부분을

developer.android.com

 

simple date format >> https://developer.android.com/reference/java/text/SimpleDateFormat

 

SimpleDateFormat  |  Android Developers

android.net.wifi.hotspot2.omadm

developer.android.com

m : minute, M : month

 

2. 선택된 시간을 분으로 변경

getTime() 이용시 1970년 1월1일부터의 시간을 milliseconds로 반환받으므로, 이를 분으로 변환하려면 일단 1000을 나눠 초로 바꾼후 60을 나눠야 분으로 표현할 때의 값을 얻을 수 있다.

https://developer.android.com/reference/java/util/Date

 

Date  |  Android Developers

android.net.wifi.hotspot2.omadm

developer.android.com

 

3. 현재 날짜 받기

system 에서 currentTimeMillis( )로 어플 사용 당시의 날짜를 받는다.

 

4. 두 날짜 사이에서 지난 시간

현재 날짜 (분단위표기상태)에서 선택한 과거 날짜(분단위표기상태)를 빼면 두 날짜 사이의 시간(정확히는 분)을 알 수 있다.

val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))
val currentDateInMinutes = currentDate.time/1000/60
val differenceInMinutes =currentDateInMinutes - selectedDateInMinutes

 

*xml 파일

5. 날짜간 분을 표시할 아이템의 id명을 새로 만들어준다.

<TextView
    android:id="@+id/tvAgeInMinutes"

*코틀린 파일

6. 변수 생성

textview로 사용자에게 글자를 보여주는 형태로 넣어놓는다.

textview >> https://developer.android.com/reference/android/widget/TextView

7.  초기화

on create 함수 안에서 super 로 onCreate 시작한 후 tvAgeInMinutes 를 초기화 해준다.

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

    val btnDatePicker: Button = findViewById(R.id.btnDatePicker)
    tvSelectedDate = findViewById(R.id.tvSelectedDate)
    tvAgeInMinutes = findViewById(R.id.tvAgeInMinutes)
    
    btnDatePicker.setOnClickListener{
        clickDatePicker()
    }
}

이렇게 등록되었으므로 이제부터 텍스트뷰 널러블 형태의 tvageInMinutes 를 메인 코틀린파일에서 사용가능

 

8. 사용

val differenceInMinutes =currentDateInMinutes - selectedDateInMinutes
tvAgeInMinutes?.text= differenceInMinutes.toString()

 

9. 

null safety

1) program works only selected date exists

선택된 날짜 있을때만 실행

    theDate?.let{
        val selectedDateInMinutes = theDate.time/1000/60
        val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))
        val currentDateInMinutes = currentDate.time/1000/60
        val differenceInMinutes =currentDateInMinutes - selectedDateInMinutes
        tvAgeInMinutes?.text= differenceInMinutes.toString()
    }
}, year, month, day)

2) " only current date exists

currentDate?.let{
    val currentDateInMinutes = currentDate.time/1000/60
    val differenceInMinutes =currentDateInMinutes - selectedDateInMinutes
    tvAgeInMinutes?.text= differenceInMinutes.toString()
}