Java - get number of days between dates [duplicate] - java

This question already has answers here:
Calculating days between two dates with Java
(16 answers)
Closed 5 years ago.
I've got a list of dates in format "yyyy-MM-dd", I'd like to have a number of days between my today date "2017-04-15" and first date from list which is higher than mine today date.

I am assuming that your events are not sorted by date. I am assuming that you can use Java 8. This is one of the tasks that have become so much easier with the java.time classes introduced in Java 8 (and backported to Java 6 and 7).
Use LocalDate.now() to get today’s date.
Iterate through your events, all the time keeping track of the closest future event date. For each event use LocalDate.parse() to convert the event’s date to a LocalDate. The 1-arg parse method fits your format. Compare with today’s date and with the earliest future event date encountered so far; if between, store as the new closest date. Use isAfter() and/or isBefore for the comparisons.
After your loop, you will either know the date or you will know that there are no future events at all. In the former case, use ChronoUnit.DAYS.between() to get the number of days from the current date to the event date.

Solution 1
If you are using joda library, then it will be easy, you can use Days.daysBetween :
Date startDate = ...;
Date endDate = ...;
int nbrDays = Days.daysBetween(new LocalDate(startDate), new LocalDate(endDate)).getDays();
Solution 2
Date startDate = ...;
Date endDate = ...;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
int day1 = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(endDate);
int day2 = cal.get(Calendar.DAY_OF_MONTH);
int nbrDays = day1 - day2;
System.out.println(nbrDays);
You have to import :
import java.util.Calendar;
import java.util.Date;
Solution 3
If your dates are in this format "yyyy-MM-dd" so you can have two dates like this :
String date1 = "1991-07-03";
String date2 = "2017-04-15";
What you should to do, split your dates with - :
String spl1[] = date1.split("-");
String spl2[] = date2.split("-");
Calculate the difference between the two dates :
int year1 = Integer.parseInt(spl1[0]);
int month1 = Integer.parseInt(spl1[1]);
int days1 = Integer.parseInt(spl1[2]);
int year2 = Integer.parseInt(spl2[0]);
int month2 = Integer.parseInt(spl2[1]);
int days2 = Integer.parseInt(spl2[2]);
//make some calculation and in the end you can get the diffidence, this work i will let it for you.

This should solve your problem.
SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd");
List<Date> dateList = new ArrayList<Date>();
try {
beforeDate = myDateFormat.parse("2016-01-13");
dateList.add(myDateFormat.parse("2016-01-10"));
dateList.add(myDateFormat.parse("2016-01-11"));
dateList.add(myDateFormat.parse("2016-01-12"));
dateList.add(myDateFormat.parse("2016-01-19"));
dateList.add(myDateFormat.parse("2016-01-20"));
dateList.add(myDateFormat.parse("2016-01-21"));
} catch (ParseException e) {
System.out.println(e.getMessage());
}
//add here
boolean check = true;
for(int i = 0; check && i < dateList.size();i++){
if(dateList.get(i).after(beforeDate)){
afterDate = dateList.get(i);
check = false;
}
}
System.out.println(beforeDate+" "+afterDate);
long days = ChronoUnit.DAYS.between(LocalDate.parse(myDateFormat.format(beforeDate)), LocalDate.parse(myDateFormat.format(afterDate)));
if(days>0){
System.out.println(days);
}else{
System.out.println(0-days);
}
if you want to sort dateList then want to get afterDate then use this code after addition of date elements in dateList
Collections.sort(dateList,new Comparator<Date>() {
#Override
public int compare(Date o1, Date o2) {
return o1.compareTo(o2);
}
});
This will allow you to sort dates in ascending order..

Related

Java Date Comparison [duplicate]

This question already has answers here:
Comparing two java.util.Dates to see if they are in the same day
(14 answers)
How to know if a Date is within the same day of other date [duplicate]
(2 answers)
Closed 6 years ago.
According to Java API public boolean before(Date when)
true if and only if the instant of time represented by this Date
object is strictly earlier than the instant represented by when; false
otherwise.
Now I have to check if date input by user is greater than current date then only it will accept the input otherwise throw exception so i tried below
if(userInputDate.before(new Date())){
throw new Exception("Some Message");
}
But if both date are same then also it going to inside if statement .Do it mean it will calculate time and then check rather than comparing date? If yes how to resolve my issue ?
Can any one tell me how to add check for this?
The method before in the class Date is comparing the millisecond between the dates, so it's not comparing just the day, it is comparing the instant of time.
You could create a method to check if the dates are not in the same day and the first date is before the second one
public static boolean isBeforeDate(Date date1, Date date2) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
boolean areTheSameDay = fmt.format(date1).equals(fmt.format(date2));
return !areTheSameDay && date1.before(date2);
}
If you can use the new time api In Java8 instead of the old Date class, you can use the class LocalDate and the method compareTo:
boolean isBefore = myLocalDate.compareTo(myOtherLocalDate) < 0
All methods on java.util.Date that allow one to separate the time of day from the day of the year are deprecated. Therefore it is better to use java.util.Calendar. Additionally one should consider that there is typically one hour in each year that is in two days when summer time ends.
Here are two ways you can do it:
public static boolean isBeforeDay(Date date1, Date date2) {
// convert date1 to noon on the same day
Calendar day1 = Calendar.getInstance(TimeZone.getDefault());
day1.setTime(date1);
day1.set(Calendar.HOUR_OF_DAY, 12);
day1.set(Calendar.MINUTE, 0);
day1.set(Calendar.SECOND, 0);
day1.set(Calendar.MILLISECOND, 0);
// convert date2 to noon on the same day
Calendar day2 = Calendar.getInstance(TimeZone.getDefault());
day2.setTime(date2);
day2.set(Calendar.HOUR_OF_DAY, 12);
day2.set(Calendar.MINUTE, 0);
day2.set(Calendar.SECOND, 0);
day2.set(Calendar.MILLISECOND, 0);
return day1.before(day2);
}
public static boolean isBeforeDay(Date date1, Date date2) {
// get yyyymmdd value from date1
Calendar day1 = Calendar.getInstance(TimeZone.getDefault());
day1.setTime(date1);
int ymd1 = 10000*day1.get(Calendar.YEAR) + 100*day1.get(Calendar.MONTH) + day1.get(Calendar.DAY_OF_MONTH);
// get yyyymmdd value from date2
Calendar day2 = Calendar.getInstance(TimeZone.getDefault());
day2.setTime(date2);
int ymd2 = 10000*day2.get(Calendar.YEAR) + 100*day2.get(Calendar.MONTH) + day2.get(Calendar.DAY_OF_MONTH);
return ymd1 < ymd2;
}

Javafx Using Date Picker

I am creating a Java Fx Application using Scene Builder. I have two Date Pickers Date1 and Date Two. I need to count the number of days between Date1 and Date2 excluding any Sunday. I have searched various answers but none that caters.
Any help much appreciated.
The following should work.
long date1 = datePicker1.getvalue().toEpochDay();
long date2 = datePicker2.getvalue().toEpochDay();
int days = (int) Math.abs(date1 - date2);
Example:
long date1 = 16322; // 09/09/2014
long date2 = 16329; // 09/16/2014
int days = (int) Math.abs(date1 - date2);
System.out.println(days); // 7 Days
Note: I do not think jfx2.0 has a built-in DatePicker, so I am assuming you are using jdk8.
Also, I pulled the the datePicker.getvalue().toEpochDay() logic from this question:
Stack Overflow: Get value from Date picker; which deals with jfx8.
The epoch in the LocalDate.toEpochDay() is the number of days since 01/01/1970.
Extra Credit
To Answer you question from the comment below, you could do the following.
int days = daysBetween(
datePicker1.getvalue(),
datePicker2.getvalue(),
Arrays.asList(DayOfWeek.SUNDAY)
);
public static int daysBetween(LocalDate start, LocalDate end, List<DayOfWeek> ignore) {
int count = 0;
LocalDate curr = start.plusDays(0); // Create copy.
while (curr.isBefore(end)) {
if (!ignore.contains(curr.getDayOfWeek()))
count++;
curr = curr.plusDays(1); // Increment by a day.
}
return count;
}

get yesterday date from timestamp [duplicate]

This question already has answers here:
Get yesterday's date using Date [duplicate]
(8 answers)
Closed 8 years ago.
I've got an object with a field timestamp with type java.sql.Timestamp;.
And I need to get objects with yesterday date from a collection.
How to get them?
I mean I need something like this
for(int i = 0; i < items.size(); i++) {
(if the items.get(i).date == yesterday_date)
(get object)
}
You can get yesterday's Date by following approach Answered by Jiger Joshi.
And by using new Timestamp(java.util.Date) you can get yesterday's timestamp, you should use Timestamp#equals to equaling two different timestamp.
if (items.get(i).date.equals(getYesterdaytimestamp())){
...
}
And there are something which you must consider while implementing this. Calender#getTime which returns Date object and date object contains date with time, so in that case your equaling date or timestamp must be exactly equals with yesterday's date and time.
If requirement is, it needs to equal just yesterday no not where time is not considerable fact. In that case you need to equals two timestamp after discarding time part.
if (equalsWithYesterday(items.get(i).date)){
...
}
...
public boolean equalsWithYesterday(Timestamp st){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); // Time part has discarded
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date yesterday = dateFormat.parse(dateFormat.format(cal.getTime())); // get yesterday's Date without time part
Date srcDate = new Date(st);
Date srcDateWithoutTime =dateFormat.parse(dateFormat.format(srcDate));
return yesterday.equals(srcDateWithoutTime ); // checks src date equals yesterday.
}
You can convert the timestamp object to date object like this:
Date date = new Date(items.get(i).getTime());
or you can simply use method Timestamp#compareTo(Date o)
items.get(i).compareTo(yesterday_date);
I hope you are not interested to compare the time?
Simply use Calendar class to extract the day, month, year etc. from the date and simply compare it.
Use Calendar#get() method to get the specific field from the date object.
How to subtract one day from the current date?
// get Calendar with current date
Calendar cal = Calendar.getInstance();
// get yesterday's date
cal.add(Calendar.DATE, -1);
// get components of yesterday's date
int month = cal.get(Calendar.MONTH) + 1; // 0 for January, 1 for Feb and so on
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);
// get yesterday's date in milliseconds
long lMillis = cal.getTime().getTime();

How do I figure out whether the current time is in between two times? [duplicate]

This question already has answers here:
How can I determine if a date is between two dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I'm trying to write a schedule program in Java and I need to figure out what time it is, and whether the current time is in between two set times. Figuring out the current time is pretty simple, but do you have any suggestions for figuring out whether it is between two times of day. For example, it is 9:33 AM on a Thursday. So I would need to figure out which scheduled section of the week that time corresponds to. How would I go about comparing the time to set periods during the week, for example an Array of sectioned times during a week such as {Monday from 9-10 AM, Tuesday from 3-4 PM, Thursday from 8-11 AM}, and seeing which section of time the current time falls between?
An efficient way to find which period any date lies within would be to have a class;
public class TimePeriod implements Comparable<TimePeriod>{
Date start;
Date end;
//Constructor, getters, setters
boolean isIn(Date date) {
return date.after(start) && date.before(end);
}
public int compareTo(TimePeriod other) {
return start.compareTo(other.start);
}
}
..and then create a sorted list of TimePeriod where you can perform a binary search.
edit:
This might make the binary search easier;
int check(Date date) {
if (isIn(date)) {
return 0;
} else if (start.after(date)) {
return -1;
} else if (end.before(date)) {
return 1;
} else {
throw new IllegalStateException("Time has gone badly wrong");
}
}
If you're using Date Class, you could do it like this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();
EDITED
As suggested by Jonathan Drapeau you could also use compareTo.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
if you want to include the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) >= 0 && after.compareTo(toCheck) <= 0
if you want to exclude the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) > 0 && after.compareTo(toCheck) < 0
You could use it too on Calendar class.
Anyway, i highly recommend you to use Calendar. It's a way precise class
you could check it like this:
Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00
if(user.after(cal1)&& user.before(cal2)){
//...
}
And to initialize and set times to Calendar, check this:
http://www.tutorialspoint.com/java/util/calendar_settime.htm
I would suggest using the Epoch time.
For a definition of Epoch time: http://en.wikipedia.org/wiki/Epoch_time
Basically, its a number of seconds after a specific date, i believe in 1989. If you translate the 3 times (the current time and the 2 times to compare to) in epoch time you can just use > < = etc.
For information on getting epoch time, Try here (has many languages): http://shafiqissani.wordpress.com/2010/09/30/how-to-get-the-current-epoch-time-unix-timestamp/
Unfortunately, my java is lacking or I'd give you some code :)
Edit:
Java epoch time code:
long epoch = System.currentTimeMillis()/1000;
Because my Java is bad and I don't have an interpreter where I am, I can only suggest using this site to help convert the other dates to epoch time: http://www.epochconverter.com/
There is before(Date) and after(Date) method in Date Class.
secondDate.before(firstDate)
If you use Calendar class, it has explicit before() and after() methods:
Calendar startDate = ...
Calendar endData = ...
isBetween = currentDate.after(startDate) && currentDate.before(endDate);

How should I properly compare two dates?

Having some trouble implementing this simple task.
Basically I want to compare two dates(some older date vs new date). I want to know if the older date is more than x months old and y days old.
int monthDiff = new Date().getMonth() - detail.getCdLastUpdate().getMonth();
int dayDiff = new Date().getDay() - detail.getCdLastUpdate().getMonth();
System.out.println("\tthe last update date and new date month diff is --> " + monthDiff);
System.out.println("\tthe last update date and new date day diff is --> " + dayDiff);
If older date is 2012-09-21 00:00:00.0, currently, it will return negative numbers. I need to find out if the older date is EXACTLY 6 months and 4 days before new Date(). I'm thinking of using absolute values of both but just can't brain today.
Edit: I know about joda but I cannot use it. I must use Java JDK.
Edit 2: I'll try out the methods listed, if all failed I'll use Joda.
JDK dates have before and after methods, returning boolean, to accomplish your task:
Date now = new Date();
Calendar compareTo = Calendar.getInstance();
compareTo.add(Calendar.MONTH, -6);
compareTo.add(Calendar.DATE, -4);
if (compareTo.getTime().before(now)) {
// after
} else {
// before or equal
}
The best way I can think of is to use Joda-Time library. Example from their site:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Or number of months:
Months m = Months.monthsBetween(startDate, endDate)
int months = m.getMonths();
where:
DateTime startDate = new DateTime(/*jdk Date*/);
DateTime endDate = new DateTime(/*jdk Date*/);
Sigh, it is up to me to add the inevitable "use JodaTime" answer.
JodaTime gives you specific data types for all significant time distances.
Date yourReferenceDate = // get date from somewhere
int months = Months.monthsBetween(
new DateTime(yourReferenceDate),
DateTime.now()
).getMonths();

Categories