How to get first and last day of the last month and first day of the year

Advertisements

what I am trying to do is get a start date and last date of the last month and also the first date of the year using the native android libraries. I have done it using LocalDate, but since it has API restriction I have to implement it so it works on all devices.

    //Get last month first data and return it as a string
    private fun getStartDateLastMonth(): String {
        val startDate= LocalDate.now()
            .minusMonths(1)
            .minusDays(LocalDate.now().dayOfMonth.toLong() - 1)
        return startDate.toString()
    }
    
    //Get last month last date and retur it as a string
    private fun getEndDateLastMonth(): String {
        val endDate = LocalDate.now()
            .minusMonths(1)
            .minusDays(LocalDate.now().dayOfMonth.toLong())
            .plusMonths(1)
        return endDate.toString()
    }
    
    //Get first day of the year
    private fun getStartDateThisYear(): String {
        val startDate = LocalDate.now()
            .with(TemporalAdjusters.firstDayOfYear())
        return startDate.toString()
    }
    
    //Get today 
    private fun getEndDateThisYear(): String {
        val endDate = LocalDate.now()
        return endDate.toString()
    }

The output has to be string but has to have this format "yyyy-MM-dd"

Any help or sugestion would be great. thanks

>Solution :

Use the Calendar class to accomplish your aim since you must develop the code to run on all devices and have API restrictions. Here is an example of how to use Calendar to implement your requirements.

Example:

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

//Get last month first data and return it as a string
private fun getStartDateLastMonth(): String {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.MONTH, -1)
    calendar.set(Calendar.DAY_OF_MONTH, 1)
    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
    return dateFormat.format(calendar.time)
}

//Get last month last date and retur it as a string
private fun getEndDateLastMonth(): String {
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.MONTH, -1)
    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH))
    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
    return dateFormat.format(calendar.time)
}

//Get first day of the year
private fun getStartDateThisYear(): String {
    val calendar = Calendar.getInstance()
    calendar.set(Calendar.MONTH, Calendar.JANUARY)
    calendar.set(Calendar.DAY_OF_MONTH, 1)
    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
    return dateFormat.format(calendar.time)
}

//Get today 
private fun getEndDateThisYear(): String {
    val calendar = Calendar.getInstance()
    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
    return dateFormat.format(calendar.time)
}

Leave a ReplyCancel reply