how to find next and previous date from date variable - java

Trying to solve a problem puzzle but not having much luck.
I have a list of dates and a Date object that get passed through to a function:
function void dateSorting(List<Date> dateList, Date newDate);
Based on the newDate i need to find out between which 2 indexes of list would this newDate fit into.
so e.g.
if date is 1/3/2015 and list contains:
INDEX, VALUE
0 , 5/1/2015
1 , 20/2/2015
2 , 15/3/2015
3 , 11/4/2015
Then function would print out/return 1 and 2 and the corresponding dates 20/2/2015 & 15/3/2015.
I have been scouring the net for pseudocode and examples but no luck. Closest i came to is closest date to newDate which doesn't help me.
Any help is appreciated.

Here, I got one for you.
void dateSorting(List<Date> dateList, Date newDate) {
for (int i = 0; i < dateList.size(); i++) {
if (newDate.before(dateList.get(i))) {
if (i != 0)
System.out.println("Previous index:" + (i - 1));
System.out.println("Next index:" + i);
break;
} else if (i == dateList.size() - 1) {
System.out.println("Previous index:" + i);
}
}
}
And I tested my code like this:
public static void main(String[] args) throws ParseException {
List<Date> dateList = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
dateList.add(sdf.parse("5/1/2015"));
dateList.add(sdf.parse("20/2/2015"));
dateList.add(sdf.parse("15/3/2015"));
dateList.add(sdf.parse("11/4/2015"));
System.out.println("Testing with 1/3/2015.");
dateSorting(dateList, sdf.parse("1/3/2015"));
System.out.println("Testing with 1/1/2015.");
dateSorting(dateList, sdf.parse("1/1/2015"));
System.out.println("Testing with 12/4/2015.");
dateSorting(dateList, sdf.parse("12/4/2015"));
}
And I got the following result:
Testing with 1/3/2015.
Previous index:1
Next index:2
Testing with 1/1/2015.
Next index:0
Testing with 12/4/2015.
Previous index:3
I believe this will be helpful for you.

Replace 17/11/2015 with Date.toString() (date iterator)
public static void main(String []args){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
date = sdf.parse("17/11/2015");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 1);
System.out.println(cal.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
These References will help you
Ref 1
Ref 2

try something like below code:
long current = newDate.getTime();
boolean flag = false;
for (int i =1; i < dateList.size(); i++){
long a = dateList.get(i-1).getTime(); long b = dateList.get(i).getTime();
if ( (a > current && b < current) || (a < current && b > current){
//newDate is in between index i-1 and i, set flag to true and do your stuff.
}
if(!flag) { //newDate did not fit between any indexes.
}
}
You should understand Calendar and Date APIs. It is preferable to use Calender API as most methods in Date are deprecated.

I think this is what you really expected:
First you have to crate a class implementing Comparator to sort your Date list :
public class DateSort implements Comparator<Date> {
#Override
public int compare(Date d1, Date d2) {
return (d1.getTime() > d2.getTime() ? 1 : -1);
}
}
Then you can get implement an algorithm to get closet max date and closest min date like below:
public class CompareDate {
public void compare(String oparation, List<Date> dateList, SimpleDateFormat sdf, Comparator<Date> comparator)
throws ParseException {
Collections.sort(dateList, comparator);
//using joda time api
DateTime givenDate = new DateTime(sdf.parse("01/03/2015"));
Days diff = Days.days(0);
OUTER:
for (Date date : dateList) {
Days newDiff = Days.daysBetween(new DateTime(date), givenDate);
switch (oparation) {
case "max-closet":
if (newDiff.getDays() < diff.getDays()) {
diff = newDiff;
System.out.println(oparation + " - " + sdf.format(date));
break OUTER;
}
break;
case "min-closet":
if (newDiff.getDays() > diff.getDays()) {
diff = newDiff;
System.out.println(oparation + " - " + sdf.format(date));
break OUTER;
}
break;
}
}
}
public static void main(String[] args) throws ParseException {
List<Date> dateList = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
dateList.add(sdf.parse("05/01/2015"));
dateList.add(sdf.parse("20/02/2015"));
dateList.add(sdf.parse("15/03/2015"));
dateList.add(sdf.parse("11/04/2015"));
new CompareDate().compare("max-closet", dateList, sdf, new DateSort());
new CompareDate().compare("min-closet", dateList, sdf, new DateSort().reversed());
//I m reversing the date list so I can sort dates to descending order.
}
}
Here I have used joda time api to get the different between two dates.

Related

Split a date into equal intervals based on a given frequency

I'm trying to break a range of dates into equal intervals. Here is the code that I'm using. (Dates are in YYYY-MM-dd format)
Integer frequency= 4;
Date startDate = '2020-02-27';
Date endDate = '2022-02-26';
String[] startD = string.valueOf(behadelPlan.Start_datum__c).split('-');
String[] endD = string.valueOf(behadelPlan.Einddatum__c).split('-');
//String[] dates;
Integer x = 0;
Integer startYear = Integer.valueof(startD[0]);
Integer endYear = Integer.valueof(endD[0]);
//while (x < 4) {
for (Integer i = startYear; i <= endYear; i++) {
Integer endMonth = i != endYear ? 11 : Integer.valueof(endD[1]) - 1;
Integer startMon = i == startYear ? Integer.valueof(startD[1]) - 1 : 0;
for (Integer j = startMon; j <= endMonth && x < frequency; j = j + 1) {
Integer month = j + 1;
String displayMonth;
if (month < 10) {
displayMonth = '0' + month;
} else {
displayMonth = String.valueOf(month);
}
List<string> slist = new string[]{string.valueOf(i), displayMonth, '01'};
string allstring = string.join(sList,'-');
System.debug(slist);
x+=1;
}
}
when I run this I get the output as
2020-02-01
2020-03-01
2020-04-01
2020-05-01
Here In my case, I want to generate the dates at equal(monthly with the day being start dates day) intervals. In the above example, I should be getting the resultant dates as 4 equal intervals (as I've given my frequency in a number of months).
Please let me know on how can I achieve this.
Here is a simple example.
startdate = '2020-01-01'
endDate = '2020-12-01'
frequency = 4
output should be
2020-01-01
2020-03-01
2020-06-01
2020-09-01
Here is how I would do it. I will us class Calendar for this.
public class FrequencyTransform {
public static void main (String[] args) {
System.out.println("Split a date into equal intervals based on a given frequency");
Integer frequency= 4;
try {
Date startDate = new SimpleDateFormat("yyyy-mm-dd").parse("2020-02-27");
Date endDate = new SimpleDateFormat("yyyy-mm-dd").parse("2021-02-26");
Calendar startCalendar = Calendar.getInstance();
startCalendar.clear();
startCalendar.setTime(startDate);
Calendar endCalendar = Calendar.getInstance();
endCalendar.clear();
endCalendar.setTime(endDate);
// id you want the interval to be months
int monthsElapsed = elapsed(startCalendar, endCalendar, Calendar.MONTH);
System.out.println("Number of months between dates:" + monthsElapsed);
int interval = monthsElapsed % frequency;
System.out.println("For the frequency 4 the interval is: " + interval);
while (!startCalendar.after(endCalendar)){
startCalendar.add(Calendar.MONTH,interval);
Date auxDate= startCalendar.getTime();
System.out.println(auxDate);
}
}
catch (ParseException ex) {
ex.printStackTrace();
}
}
private static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
}
This is just a quick example. You can take it from here. The thing is Calendar allow you to use different time units. Instead of Calendar.MONTH you can use Calendar.DATE for days, Calendar.YEAR for year. Wasn't very sure how you wanted to do the split.
Sample code ,
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SOTest {
static DateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd");
public static void main(String[] args) {
try {
String startDateString = "2020-01-01";
String endDateString = "2020-12-01";
int frequency = 4;
Date startDate = (Date)dateFormat.parse(startDateString);
Date endDate = (Date)dateFormat.parse(endDateString);
Long intervalSize = (endDate.getTime()-startDate.getTime())/frequency;
for(int i=0; i<= frequency && intervalSize > 0; i++) {
Date date = new Date(startDate.getTime()+intervalSize*i);
System.out.println("Date :: "+dateFormat.format(date));
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
output for above ::
Date :: 2020-01-01
Date :: 2020-03-24
Date :: 2020-06-16
Date :: 2020-09-08
Date :: 2020-12-01
For input :: startDate = '2020-02-27' , endDate = '2022-02-26', interval = 4
Date :: 2020-02-27
Date :: 2020-08-27
Date :: 2021-02-26
Date :: 2021-08-27
Date :: 2022-02-26

i have set of date ranges, i need to get the combined date range ,if any of the date overlaps in java [duplicate]

This question already has answers here:
Determine Whether Two Date Ranges Overlap
(39 answers)
Closed 5 years ago.
I have set of date ranges, I need to get the combined date range if any of the dates overlap in Java.
Given three sets of date ranges, if any of the dates overlap with another range of dates need to be combined.
Example:
20170101-20170331
20170101-20170430
20170430-20170501
Expected result is:
20170101-20170430
20170430-20170501
I have all the dates in String Variable. Can please any one help me to how to write the code for that. I have pasted below my code.
I want to achieve the expected results. I couldn't find out how I need to modify this code. I am a beginner, please help me to do that. I have got this sample program from StackOverflow.
package com.kkkkk.Combine;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
public class Ideone {
public static void main(String[] args) throws java.lang.Exception {
ArrayList<Interval> x = new ArrayList<>();
x.add(new Interval("20170430", "20170501")); // "20170101", "20170430"
x.add(new Interval("20170101", "20170430"));// 20170101-20170430
x.add(new Interval("20170101", "20170331"));
x = merge(x);
for (Interval i1 : x) {
System.out.println(i1.getStartDate() + " " + i1.getEndDate());
}
}
public static ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if (intervals.size() == 0 || intervals.size() == 1)
return intervals;
ArrayList<Interval> result = new ArrayList<Interval>();
Collections.sort(intervals, new IntervalComparator());
System.out.println("intervals ggggg\n" + intervals + "\n");
Interval first = intervals.get(0);
String start = first.getStartDate();
String end = first.getEndDate();
Date startDateF = null;
Date endDateF = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
startDateF = sdf.parse(start);
endDateF = sdf.parse(end);
// ArrayList<Interval> result = new ArrayList<Interval>();
for (int i = 1; i < intervals.size(); i++) {
Interval current = intervals.get(i);
Date currentEndDate = sdf.parse(current.getEndDate());
Date currentStartDate = sdf.parse(current.getStartDate());
// if ((current.getStartDate().after(endDateF)) ||
Date d1 = minDate(endDateF, currentStartDate);
if ((currentStartDate).compareTo(endDateF) <= 0) {
endDateF = maxDate(currentEndDate, endDateF);
} else {
result.add(new Interval(start, (sdf.format(endDateF))));
// start = current.start;
// end = current.end;
start = sdf.format(currentStartDate);
endDateF = (currentEndDate);
enter code here
}
}
result.add(new Interval(start, end));
// result.add(new Interval(start, (sdf.format(endDateF))));
}
catch (ParseException ex) {
ex.printStackTrace();
}
// result.add(new Interval(start, end));
return result;
// return intervals;
}
public static Date minDate(Date date1, Date date2) {
// if date1 before date2 then return date1 else return date2
return date1.before(date2) ? date1 : date2;
}
/**
* find Max Dates
*
* #param date1
* #param date2
* #return
*/
public static Date maxDate(Date date1, Date date2) {
// if date1 after date2 then return date1 else return date2
System.out.println("date max");
return date1.after(date2) ? date1 : date2;
}
}
ISO 8601
Use standard ISO 8601 formats when serializing date-time values to text. Your format complies with the “basic” version of the standard, but better to use the full format when possible:
YYYY-MM-DD
Use the standard format for a date range, using a slash character as separator:
YYYY-MM-DD/YYYY-MM-DD
If you cannot alter the input strings, split the string on the hyphen. Parse each piece as a LocalDate. Use those objects to instantiate a LocalDateRange.
LocalDate ld = LocalDate.parse( "20170101" , DateTimeFormatter.BASIC_ISO_DATE ) ;
LocalDateRange
Use the LocalDateRange class from the ThreeTen-Extra project which extends java.time class functionality. Uses the standard format when parsing and generating text.
LocalDateRange range = LocalDateRange.parse( "2017-01-01/2017-03-31" ) ;
Collect in a List<LocalDateRange>.
To sort, write a comparator that calls LocalDateRange::getStart.
Compare to another range to see if they overlap. If so, combine with a call to union.
if ( range.overlaps( otherRange ) ) {
range = range.union( otherRange ) ;
}
If they do not overlap, you have finished that round. Store this result in another List<LocalDateRange>. Start another round with the next range.
Lather, rinse, repeat.
I assume your Interval is something like this:
private static class Interval {
private String begin;
private String end;
public Interval(String begin, String end) {
this.begin = begin;
this.end = end;
}
public String getStartDate() {
return begin;
}
public String getEndDate() {
return end;
}
}
What you need to do is to merge a Interval list. A solution is sort list with start date then end date. And then store the earliest start time and latest end time in a cursor variable. A example:
public List<Interval> merge(List<Interval> intervals) {
Collections.sort(intervals, new Comparator<Interval>() {
#Override
public int compare(Interval o1, Interval o2) {
if (o1.getStartDate().equals(o2.getStartDate())) {
return o1.getEndDate().compareTo(o2.getEndDate());
}
return o1.getStartDate().compareTo(o2.getStartDate());
}
});
List<Interval> ret = new ArrayList<>();
String MAX_VAL = "99999999";
String MIN_VAL = "00000000";
String start = MAX_VAL, end = MIN_VAL;
for (Interval interval : intervals) {
if (interval.getStartDate().compareTo(end) > 0) {
if (start.compareTo(MAX_VAL) < 0) {
ret.add(new Interval(start, end));
}
start = interval.getStartDate();
end = interval.getEndDate();
} else {
if (start.compareTo(interval.getStartDate()) < 0) {
start = interval.getStartDate();
}
if (end.compareTo(interval.getEndDate()) > 0) {
end = interval.getEndDate();
}
}
}
if (start.compareTo(MAX_VAL) < 0) {
ret.add(new Interval(start, end));
}
return ret;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<MainLab.Interval> list = new ArrayList<MainLab.Interval>();
list.add(new MainLab.Interval("20170430", "20170501"));
list.add(new MainLab.Interval("20170101", "20170430"));
list.add(new MainLab.Interval("20170101", "20170331"));
for (Iterator iterator = mergeInterval(list).iterator(); iterator.hasNext();) {
Interval interval = (Interval) iterator.next();
System.out.println(interval.getStart()+ "==="+interval.getEnd());
}
}
public static List<Interval> mergeInterval(ArrayList<MainLab.Interval> list){
/*
* Sort the list , Interval class have implemented Comparable Interface.
* So we will get sorted intervals. Intervals sorted based on start of interval
*/
Collections.sort(list);
Set<MainLab.Interval> resultlist = new TreeSet<MainLab.Interval>();
List<MainLab.Interval> mergedIntervals = new ArrayList<MainLab.Interval>();
//declare date formate to parse and format date from string to and from
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
if(list.size() == 1){
//resultlist = list
return list;
}
if(list.size() > 1){
// get first interval Object. conside it as first interval
Interval mergeInterval = list.get(0);
// loop other intervals from second in the list
for(int i=1; i< list.size() ; i++){
Interval interval2 = list.get(i);
try{
Date startDate1 = sdf.parse(mergeInterval.getStart());
Date endDate1 = sdf.parse(mergeInterval.getEnd());
Date startDate2 = sdf.parse(interval2.getStart());
Date endDate2 = sdf.parse(interval2.getEnd());
// compare if current interval's start date is before merging interval's end date
// then the two intervals are overlaping
if(startDate2.compareTo(endDate1) < 0 ){
// check whether end date of current loop interval is after the merging interval.
// then we need to update the end date of merging interval with looping interval's end date
if(endDate2.compareTo(endDate1) > 0 ){
mergeInterval.setEnd(interval2.getEnd());
}
}else{
// compare if current interval's start date is after merging interval's end date
// then it must be a new interval start so swap mergInterval variable with current looping interval
mergeInterval = interval2;
}
//add merge interval to set.
resultlist.add(mergeInterval);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
mergedIntervals.addAll(resultlist);
return mergedIntervals;
}
public static class Interval implements Comparable<Interval>{
private String start;
private String end;
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
public Interval(){
}
public Interval(String start,String end){
this.start = start;
this.end = end;
}
#Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
Interval inteval = (Interval)obj;
return this.getStart().equals(inteval.getStart()) && this.getEnd().equals(inteval.getEnd()) ;
}
#Override
public int compareTo(Interval o) {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
try{
Date startDate = sdf.parse(start);
Date endDate = sdf.parse(end);
Date pstartDate = sdf.parse(o.start);
Date pendDate = sdf.parse(o.end);
return startDate.compareTo(pstartDate);
}catch(Exception ex){
ex.printStackTrace();
}
return 0;
}
}

Show time with the different hour

public static void main(String[] args) throws ParseException {
String myTime = "08:00";
int diffHour = 2;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
for (int i=0; i<=diffHour; i++) {
cal.add(Calendar.HOUR, i);
String newTime = df.format(cal.getTime());
System.out.println(newTime);
}
}
The output is:
08:00
09:00
11:00
I want it to be:
08:00
09:00
10:00
because in the different two hours only until 10:00 if we started with 08:00.
Why did the output jump from 10:00 to 11:00?
The answer by Draken is correct. You are adding i where you should be adding a number one 1.
java.time
You are also using old troublesome classes now outmoded by the java.time classes.
LocalTime
The LocalTime class represents a time-of-day-only value without date and without time zone.
LocalTime start = LocalTime.parse( "08:00" );
int hours = 2;
LocalTime time = start;
for ( int i = 0 ; i <= hours ; i++ ) {
String output = time.toString();
// Set up next loop.
time = time.plusHours( 1 );
}
cal.add(Calendar.HOUR, 1);
You're adding i, which will increase by one on each loop, so for the first it will add zero, then one, and then two. Instead, since you want to add by a concrete number, try instead to add just 1.
Though that does mean you would need to start at 07:00, the other choice is to put some logic in, but that depends on what you are expecting. Something like this could work:
for (int i=0; i<=diffHour; i++) {
if (i <= 1) {
cal.add(Calendar.HOUR, i);
} else {
cal.add(Calendar.HOUR, 1);
}
String newTime = df.format(cal.getTime());
System.out.println(newTime);
}
Here's a fiddle of it working
Try something like this:
package org.app.temputil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
public static void main(String[] args) throws ParseException {
String myTime = "08:00";
int diffHour = 2;
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
Date d = df.parse(myTime);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
for (int i = 0; i <= diffHour; i++) {
cal.add(Calendar.HOUR, i == 0 ? 0 : 1);
String newTime = df.format(cal.getTime());
System.out.println("i=[" + i + "], time=" + newTime);
}
}
}
Here is the description of your code -
for (int i=0; i<=diffHour; i++) {
cal.add(Calendar.HOUR, i);
String newTime = df.format(cal.getTime());
System.out.println(newTime);
}
Here the loop is running for i = 0, 1, 2.
For i = 0, 0 is added to calendar so that value remains same as it was earlier 8.
For i = 1, 1 is added to calendar so the value becomes 8 (earlier value) + 1 = 9
For i = 2, 2 is added to calendar so the value becomes 9 (earlier value) + 2 = 11.
To make it work,
Remove the line - cal.add(Calendar.HOUR, i);
Add this line -
if (i == 0) {
cal.add(Calendar.HOUR, 0);
} else {
cal.add(Calendar.HOUR, 1);
}
change your loop to this
for (int i=0; i<=diffHour; i++) {
String newTime = df.format(cal.getTime());
System.out.println(newTime);
cal.add(Calendar.HOUR, 1);
}

How to get saturday and sunday between two date in java [duplicate]

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;
}

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

Categories

Resources