i have 2 Date (start_date, end_date) with yyyy-MM-dd format and i want to check that if the month between in december 01 - march 31 then do something. For example my start_date is 2015-12-01 or 2016-02-01 and end_date 2016-02-12 then write something.
I have this
public void meethod(){
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = null;
Date endDate = null;
try {
startDate = df.parse(tf_start_date.getText());
endDate = df.parse(tf_end_date.getText());
} catch (ParseException e) {
e.printStackTrace();
}
if( /* what goes here? */ ) {
System.out.println("its between december-march");
} else {
}
}
tf_start_date and tf_end_date is a TextField and the value of TextFields like 2015-02-03
First, you should probably be using Calendar rather than Date. First, you'll need to construct the Calendar using a Calendar.Builder:
Calendar startCal = Calendar.Builder().setInstant(startDate);
Calendar endCal = Calendar.Builder().setInstant(endDate);
Then you can just check their months to see if they are one of the months you're looking for:
int startMonth = startCal.get(Calendar.MONTH);
if (startMonth == Calendar.DECEMBER ||
startMonth == Calendar.JANUARY ||
startMonth == Calendar.FEBRUARY ||
startMonth == Calendar.MARCH)
Similarly with endMonth.
Related
This question already has an answer here:
Calculate business days in java without saturdays, sunday and public holiday
(1 answer)
Closed 4 years ago.
I need to count for number of days except holidays(Saturday and sunday). For example my start date is 07/02/2018 and end date is 15/02/2018 (in dd/MM/yyyy format). I need to count number of working days between them. Can some please help me out? This is my code:
SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
//Date date12 = dateformat3.parse("17/07/1989");
String date1 = "11/07/2018";
String date2 = "20/07/2018";
// Date date2 = dateformat3.parse("15/10/2007");
Calendar startdate = Calendar.getInstance();
startdate.setTime(dateformat3.parse(date1));
Calendar enddate = Calendar.getInstance();
enddate.setTime(dateformat3.parse(date2));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
}
I've tried with this code but is not showing any result.
You were close, just need to increment start date inside while loop.
public static void main(String[] args) throws Exception {
System.out.println(countDays("07/02/2018", "15/02/2018"));
}
public static int countDays(String startDate, String endDate) throws Exception {
int workingDays = 0;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar startdate = Calendar.getInstance();
startdate.setTime(sdf.parse(startDate));
Calendar enddate = Calendar.getInstance();
enddate.setTime(sdf.parse(endDate));
while (!startdate.after(enddate)) {
int day = startdate.get(Calendar.DAY_OF_WEEK);
System.out.println(day);
if ((day != Calendar.SATURDAY) && (day != Calendar.SUNDAY)) {
workingDays++;
}
// increment start date, otherwise while will give infinite loop
startdate.add(Calendar.DATE, 1);
}
return workingDays;
}
As you can see, the only difference with the code I provided from yours (besides removing hard-coded values) is startdate.add(Calendar.DATE, 1);
I think you are doing wrong with your while condition.
Try this
while (ChronoUnit.DAYS.between(startdate.toInstant(), enddate.toInstant()) > 0) {
startdate.add(Calendar.DAY_OF_MONTH, 1);
if (startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startdate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
workingDays++;
}
}
If you are using Java 8 you can use :
//Here I change the format of date to make it parsable
String date1 = "2018-07-11";
String date2 = "2018-07-20";
//Parse the date to LocalDate
LocalDate start = LocalDate.parse(date1);
LocalDate end = LocalDate.parse(date2);
//iterate over the list of dates between start and end date,
//then filter only those who are not equal SATURDAY or SUNDAY, then count the result
long result = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, end))
.filter(date -> date.getDayOfWeek() != DayOfWeek.SATURDAY
&& date.getDayOfWeek() != DayOfWeek.SUNDAY
).count();
In your case it will return 7 days
This question already has answers here:
Calculate number of weekdays between two dates in Java
(20 answers)
Closed 6 years ago.
StartDate: 2016-05-8 20:16:00;
EndDate: 2016-05-30 20:16:00;
public int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (c1.after(c2)) {
if (c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY || c2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
sundays++;
saturday++;
c2.add(Calendar.DATE, 1);
c2.add(Calendar.DATE, 1);
}
System.out.println(sundays);
return saturday + sundays;
}
In this function I am trying to get total count of Saturdays and Sundays between two dates. But when I pass the date I get zero as a result. Please point out the mistake and suggest corrections.
It is not advisable to write full program but since you put effort, here is what seems to be working on my system and returning a value of 7.
public class CountWeekends {
public static void main(String[] args){
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
int count = 0;
try {
Date d1 = formatter.parse("2016-05-8 20:16:00");
Date d2 = formatter.parse("2016-05-30 20:16:00");
count = saturdaysundaycount(d1,d2);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count of Sats & Sundays = "+count);
}
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturday = 0;
while (! c1.after(c2)) {
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY ){
saturday++;
}
if(c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
sundays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Saturday Count = "+saturday);
System.out.println("Sunday Count = "+sundays);
return saturday + sundays;
}
Logic: You need to keep increment start date by one day till it
surpasses end date and keep checking day on start date.
The problem is in your while, with this piece of code is working fine for me.
Check the endDate and startDate because I guess that you are sending it in the wrong order.
while (endDate.after(startDate)) {
if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ){
sundays++;
}else if (endDate.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
saturday++;
}
endDate.add(Calendar.DATE, -1);
}
Your code does not loop through the days. Please try the following code. In the while loop it loops through all the days between the given fist date and last date. It does this by adding a day to c1 in every iteration until c1 is after c2. This gives number of Saturdays and Sundays between given dates including those two days.
public static int saturdaysundaycount(Date d1, Date d2) {
Calendar c1 = Calendar.getInstance();
c1.setTime(d1);
Calendar c2 = Calendar.getInstance();
c2.setTime(d2);
int sundays = 0;
int saturdays = 0;
while (!c1.after(c2)) {
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-E");
String formatted = format1.format(c1.getTime());
System.out.println("Current Date C1 : " + formatted);
if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
sundays++;
} else if (c1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
saturdays++;
}
c1.add(Calendar.DATE, 1);
}
System.out.println("Sundays : " + sundays);
System.out.println("Saturdays : " + saturdays);
return saturdays + sundays;
}
public static int getNumberofSundays(String d1,String d2) throws Exception{ //object in Date form
Date date1=getDate(d1);
Date date2=getDate(d2);
Calendar c1=Calendar.getInstance();
c1.setTime(date1);
Calendar c2=Calendar.getInstance();
c2.setTime(date2);
int sundays=0;
while(c1.after(c2)){
if(c2.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY){
sundays++;
c2.add(Calendar.DATE,1);
}
}
System.out.println("number of days between 2 dates"+sundays);
return sundays;
}
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
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()));
I have one problem is there. How to compare 2 date and time
enter code here
if(fromdate<=nowdt.now() && todate>= nowdt.now()){
////
}
The java.util.Date object contains methods .before(), .after and .equals() for comparing dates.
if((fromdate.before(nowDt) || fromDate.equals(nowDt))
&& ((todate.after(nowDt) || toDate.equals(nowDt))
////
}
A function to compare two date and time:
public static int compareTwoDates(Date date1, Date date2) {
if (date1 != null && date2 != null) {
int retVal = date1.compareTo(date2);
if (retVal > 0)
return 1; // date1 is greatet than date2
else if (retVal == 0) // both dates r equal
return 0;
}
return -1; // date1 is less than date2
}
You can use it where you want to. Result will be > 0 if date1 > date2, = 0 if date1 = date2, < 0 if date1 < date2. Hope it helps.
- Use Joda Time library to do this....
Eg:
Date ds = new Date();
DateTime d = new DateTime(ds);
DateTime e = new DateTime(2012,12,07, 0, 0);
System.out.println(d.isEqual(e));
System.out.println(d.toDateMidnight().isEqual(e.toDateMidnight()));
///////////////////////////// OR
System.out.println(d.withTimeAtStartOfDay().isEqual(e.withTimeAtStartOfDay()));
Try this one out to find time difference
Calendar Day = Calendar.getInstance();
Day.set(Calendar.DAY_OF_MONTH,25);
Day.set(Calendar.MONTH,7);
Day.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - Day.getTimeInMillis();
You can write
long nowTime = System.currentTimeMillis();
if(fromdate.getTime() <= nowTime && nowTime <= todate.getTime()) {
or you can write
Date nowDate = new Date();
if(fromdate.compareTo(nowDate) * nowDate.compareTo(todate) >= 0) {
or
if(!fromdate.after(nowDate) && !todate.before(nowDate))
use this answer
if((options.FromDate.before(now_Date)||options.FromDate.equals(now_Date)) && (options.ToDate.after(now_Date)|| options.ToDt.equals(now_Date)) ){
do some processs........
}