Date(from~to) 사이의 날짜 모두 구하기

나고수·2022년 2월 10일
0

1일1공부

목록 보기
8/67

[
[yyyyMMdd, yyyyMMdd],
[yyyyMMdd, yyyyMMdd] //from, to
]
이 사이에 해당하는 모든 날짜를 리턴받아봅시다요

package com.example.viewmodeltest

import java.text.SimpleDateFormat
import java.util.*

val dateFormat = SimpleDateFormat("yyyyMMdd")
val set = mutableSetOf<Calendar>()

fun main() {
    val a = listOf<Long>(20220330, 20220404)
    val b = listOf<Long>(20220211, 20220214)
    val c = listOf<Long>(20220205, 20220302)

    val array = listOf<List<Long>>(a, b, c)

    val calendarList = getLongToCalendar(array)
    getRangeSet(calendarList)

    val list = set.toList()

}

//
//[                         [
//[yyyyMMdd, yyyyMMdd ], >>>> [Calendar, Calendar ]
//[yyyyMMdd, yyyyMMdd ]  >>>> [Calendar, Calendar ]
//]                                                   ]
//
fun getLongToCalendar(array: List<List<Long>>): List<List<Calendar>> {
    return array.map {
        it.map {
            val calendar = Calendar.getInstance()
            calendar.time = dateFormat.parse(it.toString())
            calendar as Calendar
        }
    }
}

//from ~to 사이의 모든 날짜를 얻고, 중복 제거 
fun getRangeSet(calendarList: List<List<Calendar>>) {
    calendarList.forEach {
        getRangeDates(it.first(), it.last()).forEach {
            set.add(it)
        }
    }
}


//시작 날짜~ 종료 날짜 사이의 모든 날짜 list 리턴
fun getRangeDates(startDate: Calendar, endDate: Calendar): MutableList<Calendar> {
    val list = mutableListOf<Calendar>()
    //startdate가 enddate보다 작을때 동안
    while (startDate <= endDate) {
        val temp = Calendar.getInstance()
        temp.time = startDate.time
        list.add(temp)
        startDate.add(Calendar.DAY_OF_MONTH, 1) // 하루 추가하기
    }
    return list
}
profile
되고싶다

0개의 댓글