Determine how many time a Day occurs between two days in Java - java

I need to calculate how many times a Day occurs between two dates, which can be weekly or monthly.
Eg Monthly:
StartDate : 2019/01/29
EndDate: 2019/03/28
So considering the above example, the output should be 1, as this is not a leap year, Feb(28) days, also it ends on March 28.
int recordCountMonths = (int) ChronoUnit.MONTHS.between(scheduleStartDate, scheduleEndDate);
int recordCountWeeks = (int) ChronoUnit.WEEKS.between(scheduleStartDate, scheduleEndDate);
Exmaple 1
The Months implementation gives me 2 (it should return 3, considering leap year) if my date is between:
LocalDate startDate = LocalDate.of(2020, Month.JANUARY, 29);
LocalDate endDate = LocalDate.of(2020, Month.APRIL, 28);
Example2:
The Months implementation gives me 3 (it should return 2, considering 31 occurs in Jan and March only) if my date is between:
LocalDate startDate = LocalDate.of(2019, Month.JANUARY, 31);
LocalDate endDate = LocalDate.of(2019, Month.MAY, 28);
Also, the above count can be asked to calculate weekly too. In that case the count will be more. However, lets not focus on weekly for now.
I can't think of a simple way to do this.
I have tried different ways, but that gives me inaccurate results.

As promised, here's a method to solve your problem. It could be better but this should work well enough. You can make similar counting methods for other specific cases, like whatever you wanted to do with weeks.
/**
* Returns the count of the day of the start day of the month between start and end inclusively.
*/
public static int getCountOfDayOfMonthBetween(LocalDate start, LocalDate end) {
// the target day of the month to count
final int dom = start.getDayOfMonth();
// 'start' is counted as a valid day
int count = 1;
LocalDate currDate = start.plusMonths(1);
while (!currDate.isAfter(end)) {
try {
currDate = currDate.withDayOfMonth(dom);
// day of month changed, so check that the date is still valid
if (currDate.isAfter(end)) {
return count;
} else {
count++;
}
} catch (DateTimeException e) {
}
currDate = currDate.plusMonths(1);
}
return count;
}
public static void main(String[] args) {
LocalDate start1 = LocalDate.of(2020, Month.JANUARY, 29);
LocalDate end1 = LocalDate.of(2020, Month.APRIL, 28);
System.out.println(getCountOfDayOfMonthBetween(start1, end1)); // 3
LocalDate start2 = LocalDate.of(2019, Month.JANUARY, 31);
LocalDate end2 = LocalDate.of(2019, Month.MAY, 28);
System.out.println(getCountOfDayOfMonthBetween(start2, end2)); // 2
}

private int getCountOfDayOfMonthBetween(int dayOfMonth, LocalDate scheduleStartDate, LocalDate scheduleEndDate) {
if(scheduleEndDate == null) {
return -1;
}
LocalDate currDate = scheduleStartDate.withDayOfMonth(dayOfMonth);
LocalDate convertedDate = scheduleStartDate.withDayOfMonth(
scheduleStartDate.getMonth().length(scheduleStartDate.isLeapYear()));
int recordCount = 0;
while (currDate.isBefore(scheduleEndDate)) {
if(convertedDate.getDayOfMonth() >= scheduleStartDate.getDayOfMonth()) {
recordCount++;
}
currDate = currDate.plusMonths(1);
convertedDate = convertedDate.plusMonths(1);
convertedDate = convertedDate.withDayOfMonth(
convertedDate.getMonth().length(convertedDate.isLeapYear()));
}
return recordCount;
}

Related

Counting number of days of a particular month when given a duration

A duration is given.
Ex: Jan 15-March 15
I want to count the number of days which belongs to each month, in that given duration.
In this example,
number of days of January in that duration; 15
number of days of February in that duration; 28
number of days of March in that duration; 15
I'm looking for a solution other that traversing through each date of the duration and checking if Date.getMonth() = "Month I want to check against"
Is there an easier way of doing this using methods in Java Date or Java SQL Date or using any other Date type?
Map < YearMonth , Long > with lambda syntax
Here is a solution using a bit of terse code using streams and lambdas. While this solution does traverse each date of the time range, the simplicity and clarity of the code may outweigh that inefficiency.
Use LocalDate for the starting and stopping date. Use YearMonth to track each month.
LocalDate start = LocalDate.of( 2019 , 1 , 15 );
LocalDate stop = LocalDate.of( 2019 , 3 , 16 );
Make a Map to keep a number of days for each month.
Map < YearMonth, Long > map =
start
.datesUntil( stop )
.collect(
Collectors.groupingBy(
( LocalDate localDate ) -> YearMonth.from( localDate ) ,
TreeMap::new ,
Collectors.counting()
)
);
Dump to console.
{2019-01=17, 2019-02=28, 2019-03=15}
System.out.println( map );
Given a starting date, LocalDate::datesUntil provides a Stream of LocalDate objects, incremented by days.
Then just do a grouping into a SortedMap (a TreeMap) to keep months in chronological order, classified by the YearMonth and counting the days for that month in the range.
If you want the total days you can just do
long totalDays = d.datesUntil(LocalDate.of(2019, 3, 16)).count();
This is just a simple example I threw together with some basic research.
LocalDate from = LocalDate.of(2019, Month.JANUARY, 15);
LocalDate to = LocalDate.of(2019, Month.MARCH, 15);
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMM");
LocalDate date = from;
while (date.isBefore(to)) {
LocalDate endOfMonth = date.withDayOfMonth(date.lengthOfMonth());
if (endOfMonth.isAfter(to)) {
endOfMonth = to;
}
// Inclusive to exclusive comparison
long days = ChronoUnit.DAYS.between(date, endOfMonth.plusDays(1));
System.out.println(days + " days in " + date.format(monthFormatter));
date = date.plusMonths(1).withDayOfMonth(1);
}
This will output
17 days in Jan.
28 days in Feb.
15 days in Mar.
There are probably better ways to achieve the same result, but as I said, I just threw it together with a little bit of Googling and trial and error.
As has already been stated, you should avoid using the older, out-of-date and effectively deprecated Date, Calendar and associated classes.
Try this. May be something like this you want. So it set a startdate and enddate, then loop for each moth till the end date and calculate the day count. I have not tested it thoroughly, but should be close to your concept.
public static void main(String[] args) throws ParseException {
String startDateS = "01/15/2019";
String endDateS = "03/15/2019";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = dateFormat.parse(startDateS);
Date endDate = dateFormat.parse(endDateS);
while (endDate.compareTo(startDate) > 0) {
Calendar c = Calendar.getInstance();
c.setTime(startDate);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
Date endOfMonth = c.getTime();
if( endDate.compareTo(endOfMonth) > 0 )
System.out.println("Count Month " + getMonthForInt(c.get(Calendar.MONTH)) + " " + getDifferenceDays(startDate, endOfMonth));
else
System.out.println("Count Month " + getMonthForInt(c.get(Calendar.MONTH)) + " " + getDifferenceDays(startDate, endDate));
c.add(Calendar.DAY_OF_MONTH, 1);
startDate = c.getTime();
}
}
static String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11) {
month = months[num];
}
return month;
}
public static int getDifferenceDays(Date d1, Date d2) {
int daysdiff = 0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000) + 1;
daysdiff = (int) diffDays;
return daysdiff;
}
You can do the same using Java.time in Java 8.
public static void main(String[] args) throws ParseException {
String startDateS = "01/15/2019";
String endDateS = "03/15/2019";
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM/dd/yyyy");
LocalDate startDate = LocalDate.parse(startDateS, format1);
LocalDate endDate = LocalDate.parse(endDateS, format1);
while (endDate.compareTo(startDate) > 0) {
LocalDate endOfMonth = startDate.minusDays(startDate.getDayOfMonth()).plusMonths(1);
if( endDate.compareTo(endOfMonth) > 0 )
System.out.println("Count Month " + getMonthForInt(startDate) + " " + getDifferenceDays(startDate, endOfMonth));
else
System.out.println("Count Month " + getMonthForInt(startDate) + " " + getDifferenceDays(startDate, endDate));
startDate = endOfMonth.plusDays(1);
}
}
static String getMonthForInt(LocalDate startDate) {
return startDate.getMonth().getDisplayName(
TextStyle.FULL ,
Locale.US
);
}
public static long getDifferenceDays(LocalDate d1, LocalDate d2) {
// return Duration.between(d2.atStartOfDay(), d1.atStartOfDay()).toDays();
return ChronoUnit.DAYS.between(d1, d2) + 1;
}

How to calculate a full days difference between two dates considering daylight savings in java

I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0

Find the last Friday of previous month and check how many days in between current date

I need to find the Last Friday of the previous month. This month is June. I need the last Friday of May. In this case (May 29th). I am able to only find the Last Friday of current month. After I find the previous month's Friday, I need to check from how many days has it been. If it has been 5 days since the last Friday, then execute a task. Hopefully this is clear. If not, please ask and I can explain in greater detail.
public class task {
static String lastFriday;
static String dtToday;
public static void main(String[] args) {
//daysInBetween = current day - (last month's friday date)
if (daysInBetween = 5) {
//run program after 5 days
} else { //quit program }
}
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
// Gets today's date
public static String getToday() {
Calendar cal = new GregorianCalendar();
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
dtToday = date_format.format(cal.getTime());
return dtToday;
}
}
Find last Friday of any month using the method -
public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
And you may use the following method to find the diffrence between 2 days -
public int getDifferenceDays(Date d1, Date d2) {
int daysdiff=0;
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000)+1;
daysdiff = (int) diffDays;
return daysdiff;
}
You was nearly there, just add the follwing line to your getLastFriday method:
// Gets last Friday of the Month
// Need last Friday of previous Month...
public static String getLastFriday() {
Calendar cal = new GregorianCalendar();
// reduce the "current" month by 1 to get the "previous" month
cal.set(GregorianCalendar.MONTH, cal.get(GregorianCalendar.MONTH) - 1);
cal.set(GregorianCalendar.DAY_OF_WEEK, Calendar.FRIDAY);
cal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
SimpleDateFormat date_format = new SimpleDateFormat("yyyy/MM/dd");
lastFriday = date_format.format(cal.getTime());
return lastFriday;
}
Then you can read one of these question and their answers to get the difference in days: Finding days difference in java or Calculating the difference between two Java date instances.

How to get current date and add five working days in Java [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
How can I add business days to the current date in Java?
(14 answers)
Closed 8 years ago.
I want two dates.
1) Current date in MM/dd/yy format
2) Modified date which will be the adition of five business days(Mon-Fri) to current date and it should be in MMM dd, yyyy format.
So if my current is 9th june than currentDate should be 06/09/14 and modifiedDate should be Jun 13, 2014.
How to do this?
This will add working days (Mon-Fri) and will present dates in the required format.
UPDATED 6 Jul 2020
Now custom days can be used as non working days (see the list NON_BUSINESS_DAYS)
Now even the past date can be calculated as well (set businessDays as negative val)
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BusinessDateExamples {
private static final List<Integer> NON_BUSINESS_DAYS = Arrays.asList(
Calendar.SATURDAY,
Calendar.SUNDAY
);
/**
* Returns past or future business date
* #param date starting date
* #param businessDays number of business days to add/subtract
* <br/>note: set this as negative value to get past date
* #return past or future business date by the number of businessDays value
*/
public static Date businessDaysFrom(Date date, int businessDays) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
for (int i = 0; i < Math.abs(businessDays);) {
// here, all days are added/subtracted
calendar.add(Calendar.DAY_OF_MONTH, businessDays > 0 ? 1 : -1);
// but at the end it goes to the correct week day.
// because i is only increased if it is a week day
if (!NON_BUSINESS_DAYS.contains(calendar.get(Calendar.DAY_OF_WEEK))){
i++;
}
}
return calendar.getTime();
}
public static void main(String...strings) {
SimpleDateFormat s = new SimpleDateFormat("MM/dd/yy ( MMM dd, yyyy )");
Date date = new Date();
int businessDays = 5;
System.out.println(s.format(date));
System.out.print("+ " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, businessDays)));
System.out.print("- " + businessDays + " Business Days = ");
System.out.println(s.format(businessDaysFrom(date, -1 * businessDays)));
}
}
Date date=new Date();
Calendar calendar = Calendar.getInstance();
date=calendar.getTime();
SimpleDateFormat s;
s=new SimpleDateFormat("MM/dd/yy");
System.out.println(s.format(date));
int days = 5;
for(int i=0;i<days;)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
//here even sat and sun are added
//but at the end it goes to the correct week day.
//because i is only increased if it is week day
if(calendar.get(Calendar.DAY_OF_WEEK)<=5)
{
i++;
}
}
date=calendar.getTime();
s=new SimpleDateFormat("MMM dd, yyyy");
System.out.println(s.format(date));
Ref : https://stackoverflow.com/a/15339851/3603806
and https://stackoverflow.com/a/11356123/3603806
The notion of working days is not implemented in Java, it's too subject to interpretation (for example, many international companies have their own holidays). Code below uses isWorkingDay(), which only returns false for weekends - add your holidays there.
public class Test {
public static void main(String[] args) {
Calendar cal = new GregorianCalendar();
// cal now contains current date
System.out.println(cal.getTime());
// add the working days
int workingDaysToAdd = 5;
for (int i=0; i<workingDaysToAdd; i++)
do {
cal.add(Calendar.DAY_OF_MONTH, 1);
} while ( ! isWorkingDay(cal));
System.out.println(cal.getTime());
}
private static boolean isWorkingDay(Calendar cal) {
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY)
return false;
// tests for other holidays here
// ...
return true;
}
}
Here is the code sample to add dates. You may modify in order to you can only add business days.
SimpleDateFormat sdf1 = new SimpleDateFormat("MM/dd/yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd, yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
System.out.println(sdf1.format(calendar.getTime()));
calendar.add(Calendar.DATE,6);
System.out.println(sdf2.format(calendar.getTime()));

Start and end date of a current month

I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that?
For example if I select month May in a list box I need starting date that is 1 and end date that is 31.
There you go:
public Pair<Date, Date> getDateRange() {
Date begining, end;
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
setTimeToBeginningOfDay(calendar);
begining = calendar.getTime();
}
{
Calendar calendar = getCalendarForNow();
calendar.set(Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
setTimeToEndofDay(calendar);
end = calendar.getTime();
}
return Pair.of(begining, end);
}
private static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}
private static void setTimeToBeginningOfDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
private static void setTimeToEndofDay(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
PS: Pair class is simply a pair of two values.
If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime (or equivalently the Java 8 java.time.* API). Here is an example:
LocalDate monthBegin = new LocalDate().withDayOfMonth(1);
LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1);
Try LocalDate from Java 8:
LocalDate today = LocalDate.now();
System.out.println("First day: " + today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
Simple and Best, Try this One
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 0);
calendar.set(Calendar.DATE, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
Date monthFirstDay = calendar.getTime();
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Date monthLastDay = calendar.getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String startDateStr = df.format(monthFirstDay);
String endDateStr = df.format(monthLastDay);
Log.e("DateFirstLast",startDateStr+" "+endDateStr);
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = 1;
c.set(year, month, day);
int numOfDaysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("First Day of month: " + c.getTime());
c.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + c.getTime());
With the date4j library :
dt.getStartOfMonth();
dt.getEndOfMonth();
Try this Code
Calendar calendar = Calendar.getInstance();
int yearpart = 2010;
int monthPart = 11;
int dateDay = 1;
calendar.set(yearpart, monthPart, dateDay);
int numOfDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println("Number of Days: " + numOfDaysInMonth);
System.out.println("First Day of month: " + calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, numOfDaysInMonth-1);
System.out.println("Last Day of month: " + calendar.getTime());
Hope it helps.
if you have java.time.YearMonth you can do:
YearMonth startYearMonth = YearMonth.now();
java.time.LocalDate startOfMonthDate = startYearMonth.atDay(1);
java.time.LocalDate endOfMonthDate = startYearMonth.atEndOfMonth();
Date begining, ending;
Calendar calendar_start =BusinessUnitUtility.getCalendarForNow();
calendar_start.set(Calendar.DAY_OF_MONTH,calendar_start.getActualMinimum(Calendar.DAY_OF_MONTH));
begining = calendar_start.getTime();
String start= DateDifference.dateToString(begining,"dd-MMM-yyyy");//sdf.format(begining);
// for End Date of month
Calendar calendar_end = BusinessUnitUtility.getCalendarForNow();
calendar_end.set(Calendar.DAY_OF_MONTH,calendar_end.getActualMaximum(Calendar.DAY_OF_MONTH));
ending = calendar_end.getTime();
String end=DateDifference.dateToString(ending,"dd-MMM-yyyy");//or sdf.format(end);
enter code here
public static Calendar getCalendarForNow() {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(new Date());
return calendar;
}
For Java 8+, below method will given current month first & last dates as LocalDate instances.
public static LocalDate getCurrentMonthFirstDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).withDayOfMonth(1);
}
public static LocalDate getCurrentMonthLastDate() {
return LocalDate.ofEpochDay(System.currentTimeMillis() / (24 * 60 * 60 * 1000) ).plusMonths(1).withDayOfMonth(1).minusDays(1);
}
Side note: Using LocalDate.ofEpochDay(...) instead of LocalDate.now() gives much improved performance. Also, using the millis-in-a-day expression instead of the end value, which is 86400000 is performing better. I initially thought the latter would perform better than the the expression :P
public static void main(String[] args)
{
LocalDate today = LocalDate.now();
System.out.println("First day: " +
today.withDayOfMonth(1));
System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()))
}
You can implement it as below:
public void FirstAndLastDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//start date of month
calendarStart = Calendar.getInstance();
calendarStart.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
//End Date of month
calendarEnd = Calendar.getInstance();
calendarEnd.set(Integer.parseInt((new SimpleDateFormat("yyyy")).format(new Date().getTime()))
, Integer.parseInt((new SimpleDateFormat("MM")).format(new Date().getTime()))
, Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH));
Toast.makeText(this, sdf.format(calendarStart.getTime()) + "\n" + sdf.format(calendarEnd.getTime()), Toast.LENGTH_SHORT).show();
}
A very simple step to get the first day and last day of the month:
Calendar calendar = Calendar.getInstance();
// Get the current date
Date today = calendar.getTime();
// Setting the first day of month
calendar.set(Calendar.DAY_OF_MONTH, 1);
Date firstDayOfMonth = calendar.getTime();
// Move to next month
calendar.add(Calendar.MONTH, 1);
// setting the 1st day of the month
calendar.set(Calendar.DAY_OF_MONTH, 1);
// Move a day back from the date
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
// Formatting the date
DateFormat sdf = new SimpleDateFormat("dd-MMM-YY");
String todayStr = sdf.format(today);
String firstDayOfMonthStr = sdf.format(firstDayOfMonth);
String lastDayOfMonthStr = sdf.format(lastDayOfMonth);
System.out.println("Today : " + todayStr);
System.out.println("Fist Day of Month: "+firstDayOfMonthStr);
System.out.println("Last Day of Month: "+lastDayOfMonthStr);
Making it more modular, you can have one main function that calculates startDate or EndDate and than you can have individual methods to getMonthStartDate, getMonthEndDate and to getMonthStartEndDate. Use methods as per your requirement.
public static String getMonthStartEndDate(){
String start = getMonthDate("START");
String end = getMonthDate("END");
String result = start + " to " + end;
return result;
}
public static String getMonthStartDate(){
String start = getMonthDate("START");
return start;
}
public static String getMonthEndDate(){
String end = getMonthDate("END");
return end;
}
/**
* #param filter
* START for start date of month e.g. Nov 01, 2013
* END for end date of month e.g. Nov 30, 2013
* #return
*/
public static String getMonthDate(String filter){
String MMM_DD_COMMA_YYYY = "MMM dd, yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(MMM_DD_COMMA_YYYY);
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
sdf.format(GregorianCalendar.getInstance().getTime());
Calendar cal = GregorianCalendar.getInstance();
int date = cal.getActualMinimum(Calendar.DATE);
if("END".equalsIgnoreCase(filter)){
date = cal.getActualMaximum(Calendar.DATE);
}
cal.set(Calendar.DATE, date);
String result = sdf.format(cal.getTime());
System.out.println(" " + result );
return result;
}

Categories

Resources