I am trying to get to and from date where ToDate
will have previous date and FromDate
will have first date of the current month. For January it wou
public static String getCurrentMonthFirstDate(){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
//System.out.println(df.format(c.getTime()));
return df.format(c.getTime());
}
//Correction :output =02-01-2018
Joda Time
If I am understanding the question correctly, it can be done very easily by using joda time
LocalDate fromDate = new LocalDate().withDayOfMonth(1);
LocalDate toDate = new LocalDate().minusDays(1);
You can use withDayOfMonth(int dayOfMonth) method from java8 to return first day of month:
LocalDate firstDay = LocalDate.now().withDayOfMonth(1);
System.out.println(firstDay); // 2019-09-01
import java.util.Date;
import java.text.SimpleDateFormat;
...
Date currentMonth = new Date();
String yyyyMM = new SimpleDateFormat("yyyyMM").format(currentMonth);
Date firstDateOfMonth = new SimpleDateFormat("yyyyMM").parse(yyyyMM);
...
my stupid solution. but it's work for me :D
If you also want the time is set to 0 the code is:
import java.util.*;
import java.text.*;
public class DateCalculations {
public static void main(String[] args) {
Calendar aCalendar = Calendar.getInstance();
aCalendar.set(Calendar.DATE, 1);
aCalendar.set(Calendar.HOUR_OF_DAY, 0);
aCalendar.set(Calendar.MINUTE, 0);
aCalendar.set(Calendar.SECOND, 0);
Date firstDateOfCurrentMonth = aCalendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dayFirst = sdf.format(firstDateOfCurrentMonth);
System.out.println(dayFirst);
}
}
You can check online easily without compiling by using: http://www.browxy.com/
Calendar date = Calendar.getInstance();
date.set(Calendar.DAY_OF_MONTH, 1);