Search code examples
androidandroid-calendar

how to get one month from now in Calendar data type?


I want to set maximum date in my date picker dialog like this enter image description here

as you can see, it requires Calendar data type for the input.

I want the max date is always one month from current time. I have tried like this

        val now = Calendar.getInstance()
        val currentYear: Int = now.get(Calendar.YEAR)
        val currentMonth: Int = now.get(Calendar.MONTH)
        val currentDay: Int = now.get(Calendar.DAY_OF_MONTH)

        val oneMonthFromNow = now.add(Calendar.MONTH,1)

but oneMonthFromNow type is in unit, not in Calendar data type. so how to dynamically add one month from current date time ?

java or kotlin is ok


Solution

  • First thing I would say to not use Calendar class, use instead LocalDateTime. You will get many articles about how to use this class and why to use.


    Even if you want to use Calendar class, then I would say if anything not working or not returning anything, you should look into that class implementation. There must be a way to solve your problem. This way will increase your knowledge as well as debugging skills.

    So coming to your solution, you need to use like this

        val now = Calendar.getInstance()
        // val currentYear: Int = now.get(Calendar.YEAR)
        // val currentMonth: Int = now.get(Calendar.MONTH)
        // val currentDay: Int = now.get(Calendar.DAY_OF_MONTH)
    
        now.add(Calendar.MONTH,1) // Added one month 
        val oneMonthFromNow = now
        // Or 
        // val oneMonthFromNow = now.clone()
        // oneMonthFromNow.add(Calendar.MONTH,1)