I want to pass these during run time where start date would be start
date of that current month, end date should be 2 days before the
current date of the current month.
I suggest you do it using the modern date-time API as demonstrated below:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate startDate = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDate = today.minusDays(2);
// Use the following optional block if your requirement is to reset the end date
// to the start date in case it falls before the start date e.g. when the
// current date is on the 1st or the 2nd day of the month
//////////////////////// Start of optional block/////////////////////
if (endDate.isBefore(startDate)) {
endDate = startDate;
}
///////////////////////// End of optional block//////////////////////
// Get the strings representing the dates in the desired format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
String strStartDate = startDate.format(dtf);
String strEndDate = endDate.format(dtf);
System.out.println(strStartDate);
System.out.println(strEndDate);
}
}
Output:
20210401
20210419
Note: If your application is supposed to be used in a different timezone than that of your application's JVM, replace LocalDate
with ZonedDateTime
and intitialize today
with ZonedDateTime.now(ZoneId zone)
passing the applicable timezone e.g. ZoneId.of("Asia/Kolkata")
.
Learn more about the modern date-time API from Trail: Date Time.
How about using the legacy date-time API?
The legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time
, the modern date-time API* .
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.